![](/img/trans.png)
[英]Java.lang.NumberFormatException error: empty string- Java Application
[英]JavaFX Application Thread - java.lang.NumberFormatException: empty String
我在项目中工作,当用户将文本字段留空或输入未稳定条件时,我被迫创建警报,但看起来空字段的条件不起作用,如在此捕获中看到的那样。
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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.