6

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

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;
    }
}

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

4

3 回答 3

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;
    }
}
于 2012-08-31T04:54:45.710 回答
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...");
    }
}
于 2012-08-30T06:49:19.930 回答
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了不需要的语法。

于 2012-08-30T06:58:59.107 回答