我的整数验证方法中的java.util.InputMismatchException

时间:2017-04-14 20:45:10

标签: java

每次输入一个字母时都会收到java.util.InputMismatchException。我希望它显示“不正确的消息”而不是崩溃。我尝试将x作为字符串并解析输入,但问题仍然是相同的。不太清楚如何做到这一点。这是我的代码:

public static void generateDivision() {

    Random rand4 = new Random();
    Scanner keyboard6 = new Scanner(System.in);

    int random = rand4.nextInt(12);
    int random2 = rand4.nextInt(12);

    //Following two lines ensures that no remainders are present so the numbers divide evenly.
    int n = random * random2;               
    int k  = n/random;                 

    System.out.println(n + " / " + random + " = ?");
    int x = keyboard6.nextInt();

    checkUserAnswer(k, x);
}   
public static void checkUserAnswer(int n, int x) {

    try {
        if (n == x) {

            System.out.println("Correct!");
            System.out.println();


        }
        if (n != x) {

            System.out.println("Incorrect!");
            System.out.println();


        }
    } catch (InputMismatchException e) {
        System.out.println("Incorrect! That was not a number.");

    } 
    updateStats(n, x);
    tryAgain();

    }

2 个答案:

答案 0 :(得分:0)

您应该在代码中使用try / catch块,例如:

try
{
   //Code to do 
}catch(InputMismatchException ex)
{
    System.out.print("Sorry, try entering another value");
}

您将所有输入代码放在try块中,如果失败,则使用catch块捕获它,在此情况下为您提供所需的异常,即InputMismatchException。希望这会有所帮助:)

答案 1 :(得分:0)

函数nextInt()总是需要int输入,如果用户输入的内容不是int,则会抛出异常。

您可以使用try-catch语法来捕获InputMismatchException,而不是抛出异常,向用户发送消息。或者,您可以将用户输入作为String(可能是nextLine()),并自行解析int /给出相应的错误消息。但是,重新发明轮子是没有意义的,因此使用nextInt()的内置解析和try-catch是更清晰的选择。

如果您想要使用try-catch处理例外的介绍,the Java doc可能会有所帮助。