簡體   English   中英

雖然-嘗試-趕上Java

[英]While - try - catch in Java

我需要一個Java程序,要求輸入0到2之間的數字。如果用戶輸入0,則該程序結束。 如果用戶寫1,它將執行一個功能。 如果用戶寫2,它將執行另一個功能。 我還想用一條消息處理錯誤“ java.lang.NumberFormatException”,在這種情況下,請再次詢問用戶一個數字,直到他寫一個介於0和2之間的數字。

我用

public static void main(String[] args) throws IOException {
    int number = 0;
    boolean numberCorrect = false;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));



        while (numberCorrect == false){
            System.out.println("Choose a number between 0 and 2");
            String option = br.readLine();
            number = Integer.parseInt(option);

            try {
                switch(option) {
                case "0":
                    System.out.println("Program ends");
                    numberCorrect = true;
                    break;
                case "1":
                    System.out.println("You choose "+option);
                    functionA();
                    numberCorrect = true;
                    break;
                case "2":
                    System.out.println("You choose  "+option);
                    functionB();
                    numberCorrect = true;
                    break;
                default:
                    System.out.println("Incorrect option");
                    System.out.println("Try with a correct number");
                    numberCorrect = false;
                }   
            }catch(NumberFormatException z) {
                System.out.println("Try with a correct number");
                numberCorrect = false;
            }
        }
    }

但是使用此代碼,catch(NumberFormatException z)不起作用,並且程序不再要求輸入數字。

您從不真正在這里捕獲NumberFormatException 您的代碼基本上可以做到:

while (...) {
    // this can throw NumberFormatException
    Integer.parseInt(...)

    try {
        // the code in here cannot
    } catch (NumberFormatException e) {
        // therefore this is never reached
    }
}

您要在這里做的是:

while (!numberCorrect) {
    line = br.readLine();
    try {
        number = Integer.parseInt(line);
    } catch (NumberFormatException ignored) {
        continue;
    }

    // etc
}

您可以像這樣將try / catch放在parseInt周圍:

while (numberCorrect == false){
   System.out.println("Choose a number between 0 and 2");
   String option = br.readLine();

   try {
        number = Integer.parseInt(option);
    }catch(NumberFormatException z) {
       System.out.println("Try with a correct number");
       numberCorrect = false;
       option = "-1";
    }

    switch(option) {
        case "0":
        System.out.println("Program ends");
        numberCorrect = true;
        break;
...

暫無
暫無

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

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