我正在一个项目中工作,在这个项目中,当用户将文本字段保留为空时,或者当输入不稳定条件时,我被迫创建一个警报,但看起来空字段的条件不像这个捕获中看到的那样工作。
Exception in thread "JavaFX Application Thread"
java.lang.NumberFormatException: empty String
at math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at math.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
...
这是代码:
class Main extends Application
{
@Override
public void start(Stage stage1) throws Exception
{
Label lbl1= new Label("Note Controle");
lbl1.setFont(new Font(15));
TextField nc= new TextField();
//...
}
@Override
public void handle(ActionEvent arg0)
{
float c,td, mg;
c=Float.parseFloat(nc.getText());
td=Float.parseFloat(ntd.getText());
if ((!nc.getText().isEmpty()&&nc.getText()!= null) &&
(!ntd.getText().isEmpty()&&ntd.getText()!=null))
{
if ((c >= 0 && 20 >= c) && (td >= 0 && 20 >= td) )
{
mg = (float) (c * 0.6 + td * 0.2);//examen60%td20%
res.setText(String.valueOf(mg));
}
else
{
//...
}
}
}
//...
}
我真的不知道为什么,但是你正确地检查空字符串,就在那之前调用这个:
c = Float.parseFloat(nc.getText());
td = Float.parseFloat(ntd.getText());
如果nc
或ntd
持有空字符串,将抛出异常。
改为,例如:
c = Float.parseFloat(nc.getText().isEmpty() ? "0" : nc.getText());
td = Float.parseFloat(ndt.getText().isEmpty()? "0" : ntd.getText());
作为建议,这将是一个更好的方法(,因为它处理null + empty + nonNumeric值)。
public static boolean isNumeric(final String str)
{
if (str == null || str.length() == 0)
return false;
for (char c : str.toCharArray())
if (!Character.isDigit(c))
return false;
return true;
}
:
c = Float.parseFloat(!isNumeric(nc.getText()) ? "0" : nc.getText());
td = Float.parseFloat(!isNumeric(ndt.getText())? "0" : ntd.getText());