简体   繁体   English

捕获异常后请求输入

[英]Asking for input after catching an exception

I want the user to enter a number which is scanned by the following code: 我希望用户输入一个由以下代码扫描的数字:

scanner.nextInt();

If a user enters a string instead, the program throws InputMismatchException , which is obvious. 如果用户输入字符串,程序会抛出InputMismatchException ,这很明显。 I want to catch the exception in such a way that the program prompts the user to enter an input until the user enters an integer value. 我想以这样的方式捕获异常,即程序提示用户输入输入,直到用户输入整数值。

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

This code creates an infinite loop if a string is entered. 如果输入字符串,此代码将创建无限循环。

The answer to my problem is as follows: 我的问题的答案如下:

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

Put Scanner scanner = new Scanner(System.in); Scanner scanner = new Scanner(System.in); within your while loop. 在你的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...");
    }
}

How about this? 这个怎么样?

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

I have also removed continue syntax as those are not needed. 我还删除了continue语法,因为不需要这些语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM