Read input until a certain number is typed

2019-01-29 14:57发布

问题:

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); 
 }
}

回答1:

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.



回答2:

You are checking askool !=0 whereas in the while loop values are being referenced by score. Change it to while(score != 0 && askool != 0)



标签: java sum