当使用扫描仪输入错误的数据类型时,如何停止异常 [英] How to stop exception when type in wrong data type using scanner

查看:107
本文介绍了当使用扫描仪输入错误的数据类型时,如何停止异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



线程中的异常mainjava.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
在java.util.Scanner.next(Scanner.java:1530)
在java.util.Scanner.nextInt(Scanner.java: 2160)
在java.util.Scanner.nextInt(Scanner.java:2119)
在JeffSky.main(JeffSky.java:25)

当用户为int输入一个字母时。



基本上我试图找出如何保持程序运行,即使输入了错误的数据类型。就像你可以做一个if语句来通知用户,如果它们在一个给定的范围之外输入了一个int,例如从1-10开始就是不允许的。



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

  int guess; 
System.out.print(您选择的陷阱是:);

do {
guess = sean.nextInt();

if(guess> = 1&& && guess< = 6){
//如果是有效的数字,即1到6之间的陷阱,则不执行任何操作。
}
else {
System.out.print(必须在1-6之间再试一次:);
}
}

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

干杯

解决方案

来自nextInt的InputMismatchException意味着输入不是int。 您可以抓住它



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

  do {

try {
guess = sean.nextInt();

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

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

System.out.print(输入必须是1到6之间的数字);
} while(true);

旁注:调用nextInt也会孤立一个新的行字符,所以nextLine超越它。 p>

Can someone tell me how to prevent this:

"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)" when the user inputs a letter for an int.

Basically I am trying to find out how to keep the program running even though a wrong data type has been entered. Just like you can do an if statement to notify the user it is not allowed if they input an int outside a given range e.g from 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);

Cheers

解决方案

InputMismatchException from nextInt means the input is not an int. You can catch it.

This will loop until the input is a number between 1 and 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);

Side note: calling nextInt will also orphan a new line character, so nextLine advances past it.

这篇关于当使用扫描仪输入错误的数据类型时,如何停止异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆