加数java,输入0停止

好玩的

我想添加一个数字,如果用户输入数字0,他会将所有数字相乘,然后程序停止。我已经在搜索并继续尝试,但是仍然无法弄清楚。

import java.util.Scanner;

public class counting {
    public static void main (String[] args) {
        int number = 0, stop = 0;

        Scanner kb = new Scanner (System.in);
        while(true) {
            System.out.print("Enter a number (stop with 0): ");
            number += kb.nextInt();

            if (number == stop) {
                System.out.println("Outcome of the numbers " + number);
                return;
            }
        }
    }
}
马杰德·巴达维(Majed Badawi)

您需要将输入与而stop不是总计进行比较number

int number = 0, stop = 0;

Scanner kb = new Scanner (System.in);
while(true) {
     System.out.print("Enter a number (stop with 0): ");
     int input = kb.nextInt();
     number += input;
     if (input == stop) {
          System.out.println("Outcome of the numbers " + number);
          return;
     }
}

样本输入/输出:

Enter a number (stop with 0): 1
Enter a number (stop with 0): 2
Enter a number (stop with 0): 3
Enter a number (stop with 0): 0
Outcome of the numbers 6

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章