且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我得到InputMismatchException?

更新时间:2022-05-18 08:03:17

在这里你可以看到扫描仪


double nextDouble()

double nextDouble()

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

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.
}

更新

案例1

我尝试了您的代码并且没有任何问题。您收到该错误是因为您必须输入字符串。当我输入数值时,它运行没有任何错误。但是一旦我输入 String 抛出相同的异常你在问题中提到过。

I tried your code and there is nothing wrong with it. Your are getting that error because you must have entered String value. When I entered a numeric value, it runs without any errors. But once I entered String it throw the same Exception which you have mentioned in your question.

案例2

您输入的内容为输出如上所述,范围

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

I'm really wondering what you could have tried to enter. In my system, it is running perfectly without changing a single line of code. Just copy as it is and try to compile and run it.

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 等。请尝试使用此代码。

As you said, you have tried to enter 1.0, 2.8 and etc. Please try with this code.

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

Note : Please enter number one by one, on separate lines. I mean, enter 2.7, press enter and then enter second number (e.g. 6.7).