英文:
Addition numbers java and stops by entering 0
问题
我想进行加法运算,如果用户输入数字0,则将所有数字相乘,程序停止运行。我已经进行了搜索并不断尝试,但仍然无法弄清楚。
```java
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("请输入一个数字(输入0停止):");
number += kb.nextInt();
if (number == stop) {
System.out.println("所有数字的乘积:" + number);
return;
}
}
}
}
<details>
<summary>英文:</summary>
I want to make an addition and if the user enters the digit 0 he multiplies all numbers together and the program stops. I've already been searching and keep trying, but I still can't figure it out.
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;
}
}
}
}
</details>
# 答案1
**得分**: 1
你需要将输入与 ``stop`` 进行比较,而不是与总 ``number`` 进行比较:
```java
int number = 0, stop = 0;
Scanner kb = new Scanner(System.in);
while (true) {
System.out.print("输入一个数字(输入 0 停止):");
int input = kb.nextInt();
number += input;
if (input == stop) {
System.out.println("数字的总和为 " + number);
return;
}
}
示例输入/输出:
输入一个数字(输入 0 停止):1
输入一个数字(输入 0 停止):2
输入一个数字(输入 0 停止):3
输入一个数字(输入 0 停止):0
数字的总和为 6
英文:
You need to compare the input with the stop
, not the total 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;
}
}
Sample 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论