簡體   English   中英

JavaFX 應用程序線程 - java.lang.NumberFormatException:空字符串

[英]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());

如果ncntd確實包含空字符串,這將引發異常。

將其更改為,例如:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM