Conversion and Summing
Submit solution
Points:
10 (partial)
Time limit:
1.0s
Memory limit:
256M
Authors:
Problem type
Allowed languages
Java 19, Java 8
題目說明
請撰寫一個程式,由使用者輸入五個字串,嘗試將這些字串轉換為整數,最終計算所有合法整數的總和,並印出該總和數字。
如果使用者在過程中輸入了一個無法轉換為整數的字串,例如"abc",必須即時印出"abc is not a valid integer"
的錯誤信息,然後繼續嘗試加總下一個數字。
如果使用者輸入合法的數字,則默默地繼續加總。
可以利用以下的參考程式碼作為基礎,做小幅度的修改(可能在5
行以內),讓它可以滿足以上需求。
若修改正確,當程式獲得以下每一組範例輸入時,應該產生該範例的對應輸出結果。
範例輸入#1
1 a 2 b 3
範例輸出#1
a is not a valid integer
b is not a valid integer
6
範例輸入#2
abc 111 222 def 111
範例輸出#2
abc is not a valid integer
def is not a valid integer
444
範例輸入#3
1 2 3 4 5 -2 -3
範例輸出#3
15
參考程式碼
import java.util.ArrayList;
import java.util.Scanner;
public class MyProgram {
public static void main(String[] args) {
// Get five strings from the user
ArrayList<String> inputList = getUserInput(5);
// Try to convert each string and print the results
ArrayList<Integer> resultList = convertStringToInt(inputList);
// Call a function to add the integers and print the result
addAndPrint(resultList);
}
// This helper method reads a specified number of strings from the user
public static ArrayList<String> getUserInput(int numberOfInputs) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> inputList = new ArrayList<>();
for (int i = 0; i < numberOfInputs; i++) {
String input = scanner.next();
inputList.add(input);
}
return inputList;
}
// This helper method tries to convert an ArrayList of strings to an ArrayList of integers
public static ArrayList<Integer> convertStringToInt(ArrayList<String> strList) {
ArrayList<Integer> intList = new ArrayList<>();
for (String str : strList)
intList.add(Integer.parseInt(str));
return intList;
}
// This helper method adds up the integers in an ArrayList and prints the result
public static void addAndPrint(ArrayList<Integer> intList) {
int sum = 0;
for (int num : intList) {
sum += num;
}
System.out.println(sum);
}
}
Comments