Credit Card Number Checker


Submit solution

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

Authors:
Problem type
Allowed languages
Java 19, Java 8

題目說明

請撰寫一個程式,由使用者輸入四個字串片段之後,嘗試將這些字串片段組成一個信用卡號,並印出該卡號。

卡號應該全由數字組成。如果使用者在過程中輸入了一個不合法的字串片段,例如"123m",程式會及時印出"Invalid input"的錯誤信息,並且不會輸出其他內容。
假設每個輸入字串不會超過四個字元,如果是一個合法的數字但不到四個字元,會自動補零,例如123會自動補為0123。

可以利用以下的參考程式碼作為基礎,做小幅度的修改(可能在5行以內),讓它可以滿足以上需求。
若修改正確,當程式獲得以下每一組範例輸入時,應該產生該範例的對應輸出結果。


範例輸入#1

5550 1309 6672 6224

範例輸出#1

5550130966726224

範例輸入#2

5550 1309 6672 622x

範例輸出#2

Invalid input

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

public class MyProgram {
    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 creditCardNumber = buildCreditCardNumber(inputList);
        System.out.println(creditCardNumber);
    }

    // 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 credit card number from a list of strings
    public static String buildCreditCardNumber(ArrayList<String> strList) {
        // Concatenate the numbers from the list
        String creditCardNumber = "";

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

        return creditCardNumber;
    }
}

Comments

There are no comments at the moment.