JOptionPane.showInputDialog问题

时间:2013-10-20 23:32:05

标签: java string null

我可能只是累了。但无论我尝试过什么,代码总是执行。 如果String包含字符,我怎样才能获得下面的代码?

String input = JOptionPane.showInputDialog(this, "Enter your budget!", "Set Budget", 1);

    //If the input isnt empty
    System.out.println(input);
    if(!"".equals(input) || input != null){
        try{
            budgetValue = Double.parseDouble(input);
            budgetIn.setText(String.format("$%1$,.2f", budgetValue));
                setDifference();
        }
        catch(Exception ex){
            JOptionPane.showMessageDialog(this, "Unable to set budget!\n" +
                                                "Please enter a usable value!", "Sorry!", 0);
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以考虑尝试类似......

if(input != null && !input.trim().isEmpty()){...}

这应该确保只要内容不为空就执行if语句

请注意,这会修剪input个空格,因此如果您只需键入空格并按 Enter ,它将跳过if语句;)

<强>更新

要过滤input String以确保其仅包含有效的数值,您可以使用String#match和正则表达式...

if (input != null && input.matches("^\\d+(\\.(\\d+)?)?$")) {...}

这应确保仅在输入数值时执行if语句。小数(小数位)是可选的