經典教材練習「輸入整數直到 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,小數部分丟失
data != 0 && input.hasNextInt() —— 先判斷讀取值,再判斷是否有輸入,避免 0 時仍嘗試讀取下一個導致阻塞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