user27691 user27691 - 4 years ago 77
Java Question

Read input until a certain number is typed

I need to stop asking for integer inputs when zero is typed as an input and start summation immediately. My program doesn't stop when I type zero. I need it to stop and start summing up all the inputs it has gathered.

Here is what I have:

public class Inttosum {

public static void main(String[] args) {
System.out.println("Enter an integer");
Scanner kb = new Scanner(System.in);
int askool = kb.nextInt();
int sum = 0;
int score = 0;


while(askool != 0){
score = kb.nextInt();
sum += score;
}
}
}


/////////////////The final code which worked..Thank you!
public class Inttosum {

public static void main(String[] args) {
System.out.println("Enter an integer");

Scanner kb = new Scanner(System.in);
int sum = 0;
int score = 0;
do {
score = kb.nextInt();
sum += score;

}while(score != 0);
System.out.print(sum);
}
}

Answer Source

do-while

You are using something called askool as a loop condition, but updating the variable score in your loop. You could use a do-while loop. Change

while(askool != 0){
    score = kb.nextInt();
    sum += score;
}

to something like

do {
    score = kb.nextInt();
    sum += score;
}while(score != 0);

Using break

I also suggest calling Scanner.hasNextInt() before calling nextInt. And, since you don't use the score (just the sum) you could write it like,

int sum = 0;
while (kb.hasNextInt()) {
    int score = kb.nextInt();
    if (score == 0) {
        break;
    }
    sum += score;
}
System.out.print(sum);

Which will also stop (and still sum all ints) if the user enters text.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download