簡體   English   中英

當用戶輸入錯誤的字符或無效的輸入數據時,如何顯示“打印”錯誤?

[英]How to display a “print” error when the user enters wrong character or invalid input data?

我想知道是否有一種簡單的方法來顯示錯誤字符或無效輸入數據的錯誤。

public static void main(String[] args) {

    // Step 1: Create new Scanner object.
    Scanner input = new Scanner(System.in);         

    // Step 2: Prompt the user to enter today's day.
    System.out.print("Enter today’s day as an Integer (0-6): ");
    int Today = input.nextInt();

    // Step 3: Prompt the user to enter the number of days elapsed since today.
    System.out.print("Enter the number of days elapsed since today as an Integer: ");
    int DaysElapsed= input.nextInt();

    // Step 4: Compute the future day.
    int FutureDay = (Today + DaysElapsed) % 7;

    // Step 5: Printing the results.
        // Step 5.1: Today's day result depending the case.
        System.out.print("Today is ");
            // Step 5.2: Future day result depending the case.
        System.out.print(" and the future day is ");

因為你只是期望來自InputMismatchException scanner.nextInt() 'int'它將拋出一個InputMismatchException異常。 因此,您可以像這樣輕松驗證int的輸入 -

try {
   int Today = input.nextInt();
   int DaysElapsed= input.nextInt();
} catch (InputMismatchException){
   System.err.println("Input is not an integer");
}   

Scanner.nextInt()也拋出NoSuchElementExceptionIllegalStateException異常此外,您可以通過使用條件驗證輸入日期是否有效( today>=1 && today=<31

使用nextInt(),您已經將允許的值過濾為整數。 但是,如果您希望用戶輸入有限范圍內的值,您可以使用以下內容:

    int Today = 0;

    if (input.hasNextInt()) {
        if (input.nextInt() < 32 && input.nextInt() > 0) { //should be between 0-32

            Today = input.nextInt();

        } else {

            throw new Exception("Number must be between 0-32");
        }
    }

編輯:

如果您想繼續出錯:

    int Today = 0;
    if(input.hasNextInt()) {

        Today = input.nextInt();
        while (!(Today > 0 && Today < 32)){

            System.out.println("Number must be between 0-32");
            Today = input.nextInt();
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM