2013-10-20 90 views
0

我可能只是很累。但不管我尝试过的代码总是执行。 如何获取下面的代码,只有在字符串包含字符时才执行?JOptionPane.showInputDialog问题

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); 
     } 
    } 
+3

您应该在AND条件中使用AND(&&)运算符而不是OR(||)。 – ntalbs

+0

还:那system.out.println()是我看到的字符串确实是null –

+0

哦。谢谢..我一直在用Java编程一段时间,从来没有遇到过这个问题|| ..你能解释为什么请吗? –

回答

1

你可能会考虑尝试类似...

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

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

要小心的是,这种修剪input的空格,所以如果你只是输入空格并按输入,它将跳过if声明;)

更新

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

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

这应该确保if声明只有在输入数值时才执行。小数点(小数点)是可选的

+0

谢谢!无论如何,如果用户输入除double以外的内容,则会引发异常。 –

+0

我以为你想要'如果'语句执行,如果用户输入*“如果字符串包含字符?”*;) – MadProgrammer

相关问题