虽然 - 尝试 - 抓住Java

时间:2015-02-21 16:04:26

标签: java while-loop try-catch numberformatexception

我需要一个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)不起作用,程序不会再次询问数字。

2 个答案:

答案 0 :(得分:2)

你从未真正抓住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
}

答案 1 :(得分:0)

您可以将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;
...