Score Validation and Total II


Submit solution

Points: 10 (partial)
Time limit: 1.0s
Memory limit: 64M

Authors:
Problem type
Allowed languages
Java 19, Java 8

題目說明

請撰寫一個 Java 程式,允許使用者持續輸入分數字串,直到輸入特定結束符號 end(不區分大小寫)為止。

程式必須即時驗證每個輸入的字串:

  • 若字串可成功轉換為浮點數(double),則將其加入 ArrayList<Double> 中儲存,並默默繼續下一個輸入。
  • 若字串包含非法格式(例如 "A+""abc")導致無法轉換,必須即時印出錯誤訊息 <字串> is not a valid score format,然後繼續處理下一個輸入。
  • 當讀取到 end 時,停止輸入,最終計算 ArrayList 中所有有效分數的總和並印出。

請利用下方的樣板程式碼為基礎,在標記 // TODO 的空格處填入關鍵程式碼以完成上述功能。


參考程式碼

import java.util.ArrayList;
import java.util.Scanner;

public class ScoreValidatorChallenge {
    public static void main(String[] args) {
        // 呼叫動態收集與驗證函式,設定以 "end" 作為結束訊號
        ArrayList<Double> validScores = collectAndValidateScores("end");

        // 計算並顯示總分
        calculateAndDisplayTotal(validScores);
    }

    // 動態讀取輸入、即時驗證格式,並將合法分數收集至 ArrayList 中
    public static ArrayList<Double> collectAndValidateScores(String sentinel) {
        Scanner scanner = new Scanner(System.in);
        // TODO: 宣告一個適當的 ArrayList 容器用於儲存合法的 double 分數
        // TODO: 宣告 validScores

        // 持續讀取輸入,直到沒有下一個標記
        while (scanner.hasNext()) {
            String input = scanner.next();

            // TODO: 檢查輸入是否為結束訊號(忽略大小寫),若是則跳出迴圈

            // TODO: 嘗試將字串轉換為 double 並存入容器,若失敗則捕捉例外並印出錯誤訊息
            try {
                ...
            } 
            catch (...) {
                System.out.println(input + " is not a valid score format");
            }
        }
        return validScores;
    }

    // 計算並印出 ArrayList 內所有分數的總和
    public static void calculateAndDisplayTotal(ArrayList<Double> scoreList) {
        double total = 0;
        // TODO: 盤點 scoreList 的每個元素並計算總和
        for (...) {
            total += score;
        }
        System.out.println(total);
    }
}

輸入說明

使用者會輸入一行用空白分隔的字串,數量不一定。

每個字串可能是:

  • 合法的浮點數(例如:85.2 92.3 78.1
  • 非法格式的字串(例如:A+, B-

輸出說明

對於每個輸入的字串:

  • 如果該字串可以轉換成浮點數,將它加入總分中。
  • 如果該字串無法轉換為浮點數,輸出一行錯誤訊息

格式: <字串> is not a valid score format


範例測資

輸入1
85.5 90.2 A+ 88.0 B- 95.3 end
輸出1
A+ is not a valid score format
B- is not a valid score format
359.0
說明
  • 輸入:85.5, 90.2, A+, 88.0, B-, 95.3, end
  • A+ 和 B- 無法轉換為浮點數,分別輸出錯誤訊息
  • 有效分數:85.5 + 90.2 + 88.0 + 95.3 = 359.0

輸入2
100 85.5 abc 0 -50.5 xyz123 45.0 END
輸出2
abc is not a valid score format
xyz123 is not a valid score format
180.0
說明
  • 輸入:100, 85.5, abc, 0, -50.5, xyz123, 45.0, END
  • abc 和 xyz123 無法轉換為浮點數,分別輸出錯誤訊息
  • 有效分數:100 + 85.5 + 0 + (-50.5) + 45.0 = 180.0
  • 注意:結束訊號 END 不區分大小寫,也會被正確識別

Comments

There are no comments at the moment.