读取输入,直到键入特定数字

时间:2015-12-26 20:14:58

标签: java sum

当输入零作为输入并立即开始求和时,我需要停止询问整数输入。当我输入零时,我的程序不会停止。我需要它来停止并开始总结它收集的所有输入。

这就是我所拥有的:

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

/////////////////最终的代码有效。谢谢!     公共课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); 
 }
}

2 个答案:

答案 0 :(得分:1)

您正在检查askool !=0,而while循环中的值正由score引用。将其更改为while(score != 0 && askool != 0)

答案 1 :(得分:0)

do-while

您正在使用名为askool的内容作为循环条件,但更新循环中的变量score。您可以使用do-while循环。改变

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

类似

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

使用break

我还建议在致电nextInt之前致电Scanner.hasNextInt()。而且,由于您不使用score(只是sum),您可以将其编写为,

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

如果用户输入文字,也会停止(并sum所有int s。)

相关问题