while loop parsing Double.IsNaN improperly

有些话、适合烂在心里 提交于 2019-12-11 08:00:58

问题


Language: Java, IDE: eclipse mars

The program is supposed to prompt the user (using JOptionPane) for a positive value. I'm trying to catch the invalid entries. My while statement catches the negative numbers but not the strings. When a negative number is entered, the prompt is shown again, but when a string value is entered, the exception is caught and the program moves on (when it should re prompt the user).

Once a positive value has been entered, the program assigns it to a value in another class. (We're learning the MVC OOP design pattern).

Double.isNaN(Double.parseDouble(h)) ---> can anyone help me find what am I missing?

// prompt to get bandwidth from user
// check for validity
// if invalid, prompt again
try{
    h = JOptionPane.showInputDialog("Enter bandwidth as a positive number");
        // loop until parsed string is a valid double
    while (Double.isNaN(Double.parseDouble(h)) || Double.parseDouble(h) <=0)  {
            h = JOptionPane.showInputDialog("Enter bandwidth as a positive number");
        }
        // h has been set to valid double, set it to bandwidth
        model.setBandwidth(Double.parseDouble(h));  
    }catch(NumberFormatException|NullPointerException NFE){
        System.err.println("Caught exception: " + NFE.getMessage());
    }

回答1:


This is because of how parseDouble() works.

Throws:

NumberFormatException - if the string does not contain a parsable double.

(See here)

So if the String is not a double parseDouble() will not return NaN but throw an exception, which means your catch clause will be called.

To solve this problem maybe use recursively algorithm which will call your method again if an exception is thrown.




回答2:


As 4castle already stated, you need to move your try/catch block inside your while loop.

However, for validating user input you can basically stick to the following pattern:

public Foo getUserInput() {
    Foo result;
    do {
        try {
            String s = requestUserInput(); // something like Scanner.nextLine()
            result = parseUserInput(s); // something like Double.parseDouble(String)
        }
        catch(Exception exc) {
            // maybe you want to tell the user what's happened here, too
            continue;
        }
    }
    while(!isValid(result)); // something like (0 < result)
    return result;
}


来源:https://stackoverflow.com/questions/42095950/while-loop-parsing-double-isnan-improperly

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