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

解决方法

您需要将输入与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