Student ID Generator


Submit solution

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

Author:
Problem type

題目說明

請撰寫一個程式,由使用者輸入四個字串片段之後,嘗試將這些字串片段組成一個學生證號碼,並印出該證號。 證號應該全由數字組成。如果使用者在過程中輸入了一個不合法的字串片段,例如"123a",程式會及時印出"Invalid input"的錯誤信息,並且不會輸出其他內容。
假設每個輸入字串不會超過四個字元,如果是一個合法的數字但不到四個字元,會自動補零,例如87會自動補為0087。 可以利用以下的參考程式碼作為基礎,做小幅度的修改(可能在5行以內),讓它可以滿足以上需求。
若修改正確,當程式獲得以下每一組範例輸入時,應該產生該範例的對應輸出結果。


參考程式碼
import java.util.ArrayList;
import java.util.Scanner;

public class StudentIDGenerator {
    public static void main(String[] args) {
        // Get four strings from the user
        ArrayList<String> inputList = getUserInput();

        // Try to convert each string and print the results
        String studentID = buildStudentID(inputList);
        System.out.println(studentID);
    }

    // This helper method reads a specified number of strings from the user
    public static ArrayList<String> getUserInput() {
        Scanner scanner = new Scanner(System.in);
        ArrayList<String> inputList = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            String input = scanner.next();
            inputList.add(input);
        }

        return inputList;
    }

    // This method builds a student ID from a list of strings
    public static String buildStudentID(ArrayList<String> strList) {
        // Concatenate the numbers from the list
        String studentID = "";

        for (String str : strList) {
            // Convert the string to an integer and format it with leading zeros
            int num = Integer.parseInt(str);
            studentID += String.format("%04d", num);
        }

        return studentID;
    }
}

輸入

輸入一行包括四個字串片段,每個字串由空格分開

輸出

輸出該組合完成的字串(無空格、無分隔符號)
若有不合法的字串片段,則印出"Invalid input"的錯誤信息

範例輸入#1

2023 987 45 1

範例輸出#1

2023098700450001

範例輸入#2

2025 1205 abc 0123

範例輸出#2

Invalid input

Comments

There are no comments at the moment.