当我运行此代码并且不输入整数时,我收到此错误,但它仍然打印“请输入一个整数”这件事首先让我很恼火,即使我有缩进按钮,我也必须缩进每一行代码不起作用,所以我不得不在每个代码上按四次空格。现在它要求我添加更多详细信息,所以在这里...
错误:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Testing2.main(Testing2.java:22)
代码:
import java.util.Scanner;
public class Testing2 {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int RandomNum = (int) (Math.random() * 100);
System.out.println("Your random number is out of 100 is " + RandomNum + "!");
System.out.println("Please type another number");
if (!userInput.hasNextInt()) {
System.out.println("Enter an integer");
}
int numberEntered = userInput.nextInt();
int Numbered = RandomNum*numberEntered;
System.out.println(RandomNum + "*" + numberEntered + "=" + Numbered);
}
}
最佳答案
正如 Sotirious Delimanolis 所说,我看不出你的 if 有任何目的。
除此之外,您的代码非常简单。我还是不太明白你的问题。但是,如果您想删除异常,那么很简单,您需要确保输入的输入是整数类型。
扫描程序抛出InputMismatchException,以指示检索到的 token 与预期类型的模式不匹配,或者 token 超出预期类型的范围。
通常,nextInt() 和 hasNextInt() 等方法首先会跳过与分隔符模式匹配的任何输入,然后尝试返回下一个标记。
因此,请确保您处理该异常或尝试解析字符串,然后将其更改为整数或按照 Bohemian 的注释提取值。
希望这可以帮助您获得更好的清晰度。
关于Java 我收到错误但它仍然运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22752180/