首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 練習題修復:`Scanner` 循環終止條件順序導致 0 無法退出與統計邏輯錯誤

     編輯:程式設計疑難解答

經典教材練習「輸入整數直到 0,統計正負個數、總和、平均值」,常見兩個 Bug:循環條件順序導致 0 不退出、平均值整數除法截斷。

原始錯誤代碼

do {
    data = input.nextInt();
    if (data > 0) positive++;
    else negative++;  // ❌ 0 也被計入 negative
    sum += data;
    count++;
} while (input.hasNextInt() && data != 0);  // ❌ 條件順序反了

double average = sum / count;  // ❌ 整數除法後賦值 double,小數部分丟失

三大修正點

  1. 循環條件順序:data != 0 && input.hasNextInt() —— 先判斷讀取值,再判斷是否有輸入,避免 0 時仍嘗試讀取下一個導致阻塞
  2. 0 不計入正負統計:`if (data > 0) positive++; else if (data < 0) negative++;`
  3. 平均值浮點運算:`double average = (double) sum / count;` 或 `1.0 * sum / count`

修正後完整代碼

import java.util.Scanner;
public class Practice {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int data = 0, positive = 0, negative = 0, sum = 0, count = 0;
        System.out.print("Enter int value (0 for exit): ");
        while (input.hasNextInt()) {
            data = input.nextInt();
            if (data == 0) break;  // 最清晰的退出方式
            if (data > 0) positive++;
            else if (data < 0) negative++;
            sum += data;
            count++;
        }
        if (count > 0) {
            double average = 1.0 * sum / count;
            System.out.println("The number of positives is " + positive);
            System.out.println("The number of negatives is " + negative);
            System.out.println("The total is " + sum);
            System.out.println("The average is " + average);
        }
    }
}

運行示例

Enter int value (0 for exit): 1 2 -1 3 0
The number of positives is 3
The number of negatives is 1
The total is 5
The average is 1.25
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved