0

我可能只是累了。但无论我尝试过什么,代码总是会执行。我怎样才能让下面的代码只在字符串包含字符时才执行?

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

1 回答 1

1

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

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

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

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

更新

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

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

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

于 2013-10-20T23:34:37.170 回答