while循环不正确地解析Double.IsNaN [英] while loop parsing Double.IsNaN improperly

查看:126
本文介绍了while循环不正确地解析Double.IsNaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

语言:Java,IDE:eclipse mars

Language: Java, IDE: eclipse mars

该程序应该提示用户(使用JOptionPane)一个正值.我正在尝试捕获无效的条目.我的while语句捕获负数,但不捕获字符串.输入负数时,将再次显示提示,但是输入字符串值时,将捕获异常并继续执行程序(应重新提示用户).

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

一旦输入了正值,程序就会将其分配给另一个类中的值. (我们正在学习MVC OOP设计模式.)

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))--->谁能帮助我找到我所缺少的东西?

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

推荐答案

4castle所述,您需要在while循环内移动try/catch块.

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

这篇关于while循环不正确地解析Double.IsNaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆