为什么我得到InputMismatchException?

到目前为止我有这个:

public double checkValueWithin(int min, int max) { double num; Scanner reader = new Scanner(System.in); num = reader.nextDouble(); while (num  max) { System.out.print("Invalid. Re-enter number: "); num = reader.nextDouble(); } return num; } 

和这个:

 public void askForMarks() { double marks[] = new double[student]; int index = 0; Scanner reader = new Scanner(System.in); while (index < student) { System.out.print("Please enter a mark (0..30): "); marks[index] = (double) checkValueWithin(0, 30); index++; } } 

当我测试它,它不能采取双数,我得到这个消息:

 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.nextDouble(Scanner.java:2456) at MarkingSystem.checkValueWithin(MarkingSystem.java:25) at MarkingSystem.askForMarks(MarkingSystem.java:44) at World.main(World.java:6) Java Result: 1 

我该如何解决?

在这里你可以看到扫描仪的本质:

double nextDouble()

以doubleforms返回下一个标记。 如果下一个标记不是浮点数或超出范围,则抛出InputMismatchException。

试着抓住exception

 try { // ... } catch (InputMismatchException e) { System.out.print(e.getMessage()); //try to find out specific reason. } 

UPDATE

情况1

我尝试了你的代码,它没有任何问题。 您收到该错误,因为您必须输入String 。 当我输入数值时,它运行没有任何错误。 但是一旦我输入了String它就会throw你在问题中提到的相同的Exception

案例2

您输入的内容超出了我上面提到的范围

我真的很想知道你可以尝试进入什么。 在我的系统中,它运行完美,无需更改单行代码。 只需按原样复制并尝试编译并运行它。

 import java.util.*; public class Test { public static void main(String... args) { new Test().askForMarks(5); } public void askForMarks(int student) { double marks[] = new double[student]; int index = 0; Scanner reader = new Scanner(System.in); while (index < student) { System.out.print("Please enter a mark (0..30): "); marks[index] = (double) checkValueWithin(0, 30); index++; } } public double checkValueWithin(int min, int max) { double num; Scanner reader = new Scanner(System.in); num = reader.nextDouble(); while (num < min || num > max) { System.out.print("Invalid. Re-enter number: "); num = reader.nextDouble(); } return num; } } 

正如您所说,您已尝试输入2.8等。请尝试使用此代码。

注意:请在单独的行中逐个输入数字。 我的意思是,输入2.7 ,按回车键然后输入第二个号码(例如6.7 )。

而不是使用点,如:1.2,尝试输入如下:1,2。

我遇到了同样的问题。 奇怪,但原因是对象Scanner根据系统的本地化来解释分数。 如果当前本地化使用逗号分隔部分分数,则带有点的分数将变为String类型。 因此错误……

您是否向控制台提供写入输入?

 Scanner reader = new Scanner(System.in); num = reader.nextDouble(); 

如果只输入456之类的数字,则返回double。如果输入字符串或字符,则在尝试执行num = reader.nextDouble()时会抛出java.util.InputMismatchException。

由于您有手动用户输入循环,在扫描仪读取您的第一个输入后,它将通过回车/返回到下一行也将被读取; 当然,这不是你想要的。

你可以试试这个

 try { // ... } catch (InputMismatchException e) { reader.next(); } 

或者,您可以在通过调用读取下一个双输入之前使用该回车

reader.next()