在这里你可以看到Scanner的本质:
double nextDouble()
Returns the next token as a double. If the next token is not a float or
is out of range, InputMismatchException is thrown.
试着抓住异常
try {
// ...
} catch (InputMismatchException e) {
System.out.print(e.getMessage()); //try to find out specific reason.
}
UPDATE
情况1
我尝试了你的代码,它没有任何问题.您收到错误是因为您必须输入字符串值.当我输入一个数值时,它运行没有任何错误.但是一旦我输入了String,它就会抛出你在问题中提到的相同的异常.
案例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;
}
}
如你所说,你试图输入1.0,2.8等.请尝试使用此代码.
注意:请在单独的行中逐个输入数字.我的意思是,输入2.7,按回车键然后输入第二个号码(例如6.7).