如何使用扫描仪键入错误的数据类型时停止异常

时间:2013-12-19 23:43:57

标签: java exception

有人可以告诉我如何防止这种情况:

"Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:909) at java.util.Scanner.next(Scanner.java:1530) at java.util.Scanner.nextInt(Scanner.java:2160) at java.util.Scanner.nextInt(Scanner.java:2119) at JeffSky.main(JeffSky.java:25)" 当用户输入int的字母时。

基本上我试图找出即使输入了错误的数据类型也能保持程序运行的方法。就像你可以做一个if语句通知用户一样,如果他们输入一个给定范围之外的int,例如1-10,则不允许这样做。

for(int x = 1; x< = 3; x ++){

int guess;
        System.out.print("Your chosen trap is: "); 

        do{
            guess=sean.nextInt();

            if(guess>=1 && guess<=6){   
                //do nothing if is a valid number i.e a trap between 1 and 6.
            }                                           
            else {
                System.out.print("Has to be between 1-6. Try again: ");
            }
        }

        while(guess<1 || guess>6);

干杯

2 个答案:

答案 0 :(得分:4)

nextInt的InputMismatchException意味着输入不是int。 You can catch it

这将循环,直到输入是1到6之间的数字:

do {

    try {
        guess = sean.nextInt();

        if (guess >= 1 && guess <= 6) break;

    } catch (InputMismatchException e) {
    } finally {
        sean.nextLine();
    }

    System.out.print("Input must be a number between 1 and 6: ");
} while (true);

旁注:调用nextInt也会孤立一个换行符,所以nextLine会超越它。

答案 1 :(得分:2)

使用scanner.nextInt();等方法时,通常会抛出此错误。如果您想避免使用String input = scanner.next(),请检查input以查看它是否可以表示为Integer