Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

java - Why am I getting InputMismatchException?

So far I have this:

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

and this:

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++;
    }
}

When I test this, it can't take double number and I got this message:

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

How do I fix this?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of using a dot, like: 1.2, try to input like this: 1,2.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...