我可能只是累了。但无论我尝试过什么,代码总是执行。 如果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);
}
}
答案 0 :(得分:1)
您可以考虑尝试类似......
if(input != null && !input.trim().isEmpty()){...}
这应该确保只要内容不为空就执行if
语句
请注意,这会修剪input
个空格,因此如果您只需键入空格并按 Enter ,它将跳过if
语句;)
<强>更新强>
要过滤input
String
以确保其仅包含有效的数值,您可以使用String#match
和正则表达式...
if (input != null && input.matches("^\\d+(\\.(\\d+)?)?$")) {...}
这应确保仅在输入数值时执行if
语句。小数(小数位)是可选的