I am working in project where I was forced to create an alert when the user left the text field empty or when the input does not stasifiying the condition but it look that the condition for empty field does not work as seen on this capture .
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)
...
This is the code:
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
{
//...
}
}
}
//...
}
I don't really know why, but you correctly check for empty strings and just before that invoke this:
c = Float.parseFloat(nc.getText());
td = Float.parseFloat(ntd.getText());
Which will throw the exception if nc
or ntd
hold empty strings, indeed.
Change it to, for example:
c = Float.parseFloat(nc.getText().isEmpty() ? "0" : nc.getText());
td = Float.parseFloat(ndt.getText().isEmpty()? "0" : ntd.getText());
As a suggestion, this would be a better approach ( as it handles null + empty + nonNumeric values ).
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;
}
So:
c = Float.parseFloat(!isNumeric(nc.getText()) ? "0" : nc.getText());
td = Float.parseFloat(!isNumeric(ndt.getText())? "0" : ntd.getText());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.