昨天雖然可以自選天數,但會是必須要輸入自己一摋輸入的天數的狀態,今天要讓程式碼有可以提前結束統計的功能
要讓使用者一開始不需要輸入天數,每天依序輸入血壓資料,如果輸入-1就會提前結束但一樣能夠計算平均等等
新增程式碼:
1.用while(true)改掉原本的for,因為while是無限迴圈,天數不需要事先決定,使用者可以自己選擇輸入多久
int dayIndex = 1;
while (true) {
System.out.println("第 " + dayIndex + " 天 (輸入 -1 結束):");
System.out.print("請輸入收縮壓:");
int systolic = scanner.nextInt();
if (systolic == -1) break; // 結束輸入
System.out.print("請輸入舒張壓:");
int diastolic = scanner.nextInt();
if (diastolic == -1) break; // 結束輸入
System.out.print("請輸入脈搏:");
int pulse = scanner.nextInt();
if (pulse == -1) break; // 結束輸入
records.add(new BloodPressureRecord(systolic, diastolic, pulse));
dayIndex++;
}
2.輸入-1就跳出迴圈,收縮壓、舒張壓、脈搏都用一樣的方法
int systolic = scanner.nextInt();
if (systolic == -1) break;
3.對應一開始就輸入-1的狀態
如果一開始就輸入-1的話就會直接結束不會有數據所以這時候就要告知程式不需要計算平均,直接告訴使用者「沒有輸入數據」
if (!records.isEmpty()) {
} else {
System.out.println("\n沒有輸入任何紀錄。");
}
執行結果:
輸入四天後自行提前結束的狀況
第 1 天 (輸入 -1 結束):
請輸入收縮壓:100
請輸入舒張壓:58
請輸入脈搏:122
第 2 天 (輸入 -1 結束):
請輸入收縮壓:96
請輸入舒張壓:53
請輸入脈搏:107
第 3 天 (輸入 -1 結束):
請輸入收縮壓:100
請輸入舒張壓:96
請輸入脈搏:80
第 4 天 (輸入 -1 結束):
請輸入收縮壓:98
請輸入舒張壓:58
請輸入脈搏:94
第 5 天 (輸入 -1 結束):
請輸入收縮壓:-1
=== 血壓紀錄 ===
第 1 天: 收縮壓=100 舒張壓=58 脈搏=122
第 2 天: 收縮壓=96 舒張壓=53 脈搏=107
第 3 天: 收縮壓=100 舒張壓=96 脈搏=80
第 4 天: 收縮壓=98 舒張壓=58 脈搏=94
=== 平均值 ===
平均收縮壓: 98.5
平均舒張壓: 66.25
一開始就結束的狀況
第 1 天 (輸入 -1 結束):
請輸入收縮壓:-1
=== 血壓紀錄 ===
沒有輸入任何紀錄。