整数验证方法中的java.util.InputMismatchException
每次输入字母时,我都会得到java.util.InputMismatchException。我希望它显示“错误消息”,而不是崩溃。我试着把x变成一个字符串并解析输入,但问题仍然是一样的。不太清楚怎么做。这是我的密码:整数验证方法中的java.util.InputMismatchException,java,Java,每次输入字母时,我都会得到java.util.InputMismatchException。我希望它显示“错误消息”,而不是崩溃。我试着把x变成一个字符串并解析输入,但问题仍然是一样的。不太清楚怎么做。这是我的密码: public static void generateDivision() { Random rand4 = new Random(); Scanner keyboard6 = new Scanner(System.in); int random = r
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();
}
您应该在代码中使用try/catch块,例如:
try
{
//Code to do
}catch(InputMismatchException ex)
{
System.out.print("Sorry, try entering another value");
}
您将所有输入代码放入try块,如果它失败,您将使用catch块捕获它,并为其提供您想要的特定异常。在本例中,它是InputMismatchException。希望这有帮助:)函数nextInt()
总是需要int
输入,如果用户输入的内容不是int
,则会引发异常
您可以使用try catch
语法捕获inputmaschException
,而不是抛出异常,而是向用户传递消息。或者,您可以将用户输入作为字符串
(可能是nextLine()
),并解析int
/自己给出适当的错误消息。但是,重新设计轮子是没有意义的,因此使用nextInt()
的内置解析和try catch
是更干净的选择
如果您想了解如何使用
try catch
处理异常,这可能会很有帮助。如果有一种方法可以尝试某些操作,然后捕获异常并在这些情况下执行某些操作。。。就像上面描述的一样,我尝试使用try-catch块,但它仍然显示错误,而不是打印一条“不正确”的消息,这不是try/catch块的错误-问题是如何编码它。如果您向我们展示了该代码,我们可能能够解释为什么会出现这种情况。您没有将try块放在从用户处获取输入的代码段周围,这就是问题所在。可以抛出错误的代码段是需要进入try块的部分。您的print语句不会抛出要捕获的输入异常。哦,实际上这很有意义。我非常专注于检查数字的方法。谢谢你的澄清,我刚试过这么做。当我测试它的时候。错误仍然会弹出,并且我的消息不会显示。你能用try-catch块发布你的代码吗?