java.util.Scanner : why my nextDouble() does not prompt?

此生再无相见时 提交于 2019-12-12 21:19:05

问题


import java.util.*;

public class June16{
    public static void main(String[] args){
        Scanner kb = new Scanner(System.in);
        double b=0;
           boolean checkInput = true;
        do{
            try{
                System.out.println("Input b : ");
                b = kb.nextDouble();
                checkInput = false;
            }catch(InputMismatchException ime){
            }
        }while(checkInput);
    }
}

After InputMismatchException is thrown, why my program not prompt for input? :D


回答1:


From the documentation:

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

This is why you end up in an infinite loop if you don't enter a valid double. When you handle the exception, move to the next token with kb.next().




回答2:


Because if the Scanner.nextDouble() failes it leaves the token on the queue, (which is then read again and again causing it to fail over and over again).

Try the following:

try {
    // ...
} catch (InputMismatchException ime) {
    kb.next();  // eat the malformed token.

}

ideone.com demo illustrating working example




回答3:


This is due to the fact that nextDouble will take the decimal number you entered, but there is still a carriage return that you enter that was not read by the scanner. The next time it loops it reads the input, but wait! there is a carriage return there, so... no need to scan anything. It just processes the carriage return. Of course, the program finds that it is not a double, so you get an exception. How do you fix it? Well, have something that scans whatever leftovers were left by the nextDouble (namely a next()) and then scan the next double again.



来源:https://stackoverflow.com/questions/6374623/java-util-scanner-why-my-nextdouble-does-not-prompt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!