Score Validation and Total
題目說明
請撰寫一個程式,輸入五個分數字串,嘗試將這些字串轉換為有效的分數整數,最終計算所有有效分數的總和,並印出該總和數字。
如果在過程中輸入了一個無法轉換為整數的字串,例如"A+",必須即時印出"A+ is not a valid score format"
的錯誤信息,然後繼續嘗試加總下一個分數。
如果輸入合法的分數數字,則默默地繼續加總。
可以利用以下的參考程式碼作為基礎,做小幅度的修改(可能在5
行以內),讓它可以滿足以上需求。
若修改正確,當程式獲得以下每一組範例輸入時,應該產生該範例的對應輸出結果。
參考程式碼
import java.util.ArrayList;
import java.util.Scanner;
public class ExamScoreValidator {
public static void main(String[] args) {
// Get five score strings from the teacher
ArrayList<String> scoreInputs = getScoreInput(5);
// Try to validate each score and collect valid ones
ArrayList<Integer> validScores = validateScoreFormat(scoreInputs);
// Calculate and display the total score
calculateAndDisplayTotal(validScores);
}
// This helper method reads a specified number of score strings from the teacher
public static ArrayList<String> getScoreInput(int numberOfScores) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> scoreInputs = new ArrayList<>();
for (int i = 0; i < numberOfScores; i++) {
String scoreInput = scanner.next();
scoreInputs.add(scoreInput);
}
return scoreInputs;
}
// This helper method tries to validate score format and convert to integers
public static ArrayList<Integer> validateScoreFormat(ArrayList<String> scoreStrings) {
ArrayList<Integer> validScores = new ArrayList<>();
for (String scoreStr : scoreStrings)
validScores.add(Integer.parseInt(scoreStr));
return validScores;
}
// This helper method calculates the total score and prints the result
public static void calculateAndDisplayTotal(ArrayList<Integer> scoreList) {
int total = 0;
for (int score : scoreList) {
total += score;
}
System.out.println(total);
}
}
輸入
使用者會輸入一行共 5 個用空白分隔的字串,代表五個分數輸入。
每個字串可能是:
合法的整數數字(例如:85, 92, 78)
非法格式的字串(例如:A+, B-)
輸出
對於每個輸入的字串:
如果該字串可以轉換成整數,將它加入總分中。
如果該字串無法轉換為整數,輸出一行錯誤訊息(格式如下)<字串> is not a valid score format
範例輸入#1
85 A+ 92 B- 78
範例輸出#1
A+ is not a valid score format
B- is not a valid score format
255
範例輸入#2
abc def ghi jkl mno
範例輸出#2
abc is not a valid score format
def is not a valid score format
ghi is not a valid score format
jkl is not a valid score format
mno is not a valid score format
0
Comments