添加数字 java 并通过输入 0 停止
Addition numbers java and stops by entering 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;
}
}
样本input/output:
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
我想做一个加法,如果用户输入数字 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;
}
}
样本input/output:
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