【问题标题】:Finding the sum of all elements of a sequence, ending with the number 0 using do-while loop in Java使用Java中的do-while循环查找序列的所有元素的总和,以数字0结尾
【发布时间】:2023-03-29 10:59:01
【问题描述】:

我是初学者。如果有人用 Java 以简单的方式解决我的问题,我将不胜感激。

问题: 求一个序列中所有元素的和,以数字 0 结尾。 数字 0 本身不包含在序列中,并用作停止的标志。 样本输入: 3 6 8 0 和 样本输出: 17

我正在编写以下程序:

 import java.util.Scanner;
 class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int sum = 0;
        do {
            sum += scanner.nextInt();
        } while (scanner.nextInt() != 0);
        System.out.println(sum);
    }

我得到的如下:

输入: 3 6 8 0

输出:

11

【问题讨论】:

  • 你调用了两次 nextInt (每个读取一个 int)所以实际上你使用 1 over 2
  • 构造 int i; while ((i = scanner.nextInt()) != 0) {} 会更适合手头的任务。
  • 谢谢。现在我明白了。 @azro

标签: java


【解决方案1】:

你的代码有问题

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int sum = 0;
    do {
        sum += scanner.nextInt(); // consuming an int from keyboard with nextInt()
    } while (scanner.nextInt() != 0); // consuming another int from keyboard with nextInt()
    System.out.println(sum);

用于输入3 6 8 0

 sum += scanner.nextInt(); //this nextInt() consumes 3 now sum has 3
 scanner.nextInt() != 0 // this nextInt() consumes 6 but does not add to sum now sum has 3 only the 6 is ignored 

 sum += scanner.nextInt(); // same here this consumes 8 and add to sum now sum has 11 which is the output
 scanner.nextInt() != 0 // this nextInt() consumes 0 which fails the condition 

简而言之,您忽略了每一秒的输入

修复

Scanner scanner = new Scanner(System.in);
         int sum = 0;
         int num = 0;
         while((num = scanner.nextInt()) != 0) { // nextInt() is called only once and value is cashed in num
             sum += num; // add this num to sum
         }
         System.out.println(sum); // prints 17 as expected

【讨论】:

    【解决方案2】:

    请尝试以下代码

    class Main {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            int sum = 0;
            int checker = 0;
            do {
                checker = scanner.nextInt();
                sum += checker;
    
            } while (checker != 0);
            System.out.println(sum);
        }
    }
    

    在来自scanner.nextInt() 中的while loop 的代码值被错过添加。这导致了一个问题

    【讨论】:

      猜你喜欢
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多