捕获异常后请求输入

时间:2012-08-30 06:45:36

标签: java java.util.scanner numberformatexception inputmismatchexception

我希望用户输入一个由以下代码扫描的号码:

scanner.nextInt();

如果用户输入字符串,程序会抛出InputMismatchException,这很明显。我想以这样的方式捕获异常,即程序提示用户输入输入,直到用户输入整数值。

Scanner scanner = new Scanner(System.in);
while(true) {
    try {
        System.out.println("Please enter a number: ");
        int input = scanner.nextInt();
        System.out.println(input);
        //statements
        break;
    }
    catch(InputMismatchException | NumberFormatException ex ) {
        continue;
    }
}

如果输入字符串,此代码会创建一个无限循环。

3 个答案:

答案 0 :(得分:4)

我的问题的答案如下:

Scanner scanner = new Scanner(System.in);
while(true) {
    try {
        System.out.println("Please enter a number: ");
        int input = scanner.nextInt();
        System.out.println(input);
        //statements
        break;
    }
    catch(InputMismatchException | NumberFormatException ex ) {
        scanner.next();//new piece of code which parses the wrong input and clears the //scanner for new input
        continue;
    }
}

答案 1 :(得分:3)

Scanner scanner = new Scanner(System.in);放在while循环中。

Scanner scanner;
while(true) {    
    try {
        System.out.println("Please enter a number: ");
        scanner = new Scanner(System.in);
        int input = scanner.nextInt();
        System.out.println(input);
        //statements
        break;
    }
    catch(InputMismatchException | NumberFormatException ex ) {
        System.out.println("I said a number...");
    }
}

答案 2 :(得分:0)

这个怎么样?

while(true) {    
    try {
        System.out.println("Please enter a number: ");
        Scanner scanner = new Scanner(System.in);
        int input = scanner.nextInt();
        System.out.println("\n\nEntered number is : " + input);
        break;
    } catch(InputMismatchException | NumberFormatException ex ) {
        System.out.println("\n\nInput was not a number. Please enter number again : ");
    } catch(Exception e ) {
        System.out.println("\n\nException caught :: " + e);
    }
}

我还删除了continue语法,因为不需要这些语法。