我可能只是累了。但无论我尝试什么,代码总是会执行。 如何让下面的代码仅在字符串包含字符时执行?
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);
}
}
最佳答案
您可能会考虑尝试诸如...
if(input != null && !input.trim().isEmpty()){...}
这应该确保只要内容不为空就执行 if
语句
但请注意,这会修剪 input
中的空格,因此如果您只键入空格并按 Enter,它将跳过 if
> 声明;)
已更新
要过滤输入
字符串
以确保它仅包含有效的数值,您可以使用 String#match
和正则表达式...
if (input != null && input.matches("^\\d+(\\.(\\d+)?)?$")) {...}
这应该确保 if
语句仅在您输入数值时执行。小数点(小数位)是可选的
关于java - JOptionPane.showInputDialog 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19484116/