读取输入,直到输入某个数字

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

这是我有的:

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

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 )。

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