加法数字 Java,并且通过输入 0 停止。

huangapple go评论59阅读模式
英文:

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&#39;ve already been searching and keep trying, but I still can&#39;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(&quot;Enter a number (stop with 0): &quot;);
        number += kb.nextInt();

        if (number == stop) {
            System.out.println(&quot;Outcome of the numbers &quot; + 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(&quot;Enter a number (stop with 0): &quot;);
     int input = kb.nextInt();
     number += input;
     if (input == stop) {
          System.out.println(&quot;Outcome of the numbers &quot; + 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

huangapple
  • 本文由 发表于 2020年10月4日 03:26:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/64188168.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定