我在一个项目中工作,在该项目中,当用户将文本字段留空或输入无法稳定条件但看上去空字段的条件不起作用时,我不得不创建一个警报,如此捕获所示。
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());
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句