簡體   English   中英

Java NetBeans-如果jtextfield值為空,如何將jtextfield值分配為零

[英]Java netbeans - how assign jtextfield value to zero if jtextfield value is empty

    double B=Double.parseDouble(emp_txt2.getText());
    double C=Double.parseDouble(nopay_txt3.getText());
    double E=Double.parseDouble(wop_txt4.getText());
    double F=Double.parseDouble(wop_txt5.getText());

   double f =B+C+E+F;
   String p = String.format("%.2f",f);
   lb1_total3.setText(p);

當jtextfield為空時,我想將B,C,E,F的雙精度值賦給零。

您可以使用此方法代替Double.parseDouble

public static double tryParsDouble(String s, double defaultValue) {
     if (s == null) return defaultValue;

     try {
         return Double.parseDouble(s);
     } catch (NumberFormatException x) {
         return defaultValue;
     }  
}

然后:

double F = tryParsDouble(wop_txt5.getText(), 0.0);

嘗試在輸入值emp_text2文本字段和代碼分別返回下列值: "" " " "1" "1.1" "-1.1" "1.0 "返回0.00.01.01.1-1.11.0

如果輸入為"1.1x"怎樣? 這將引發NumberFormatException應用程序需要弄清楚該怎么做。

double value = getDoubleValue(emp_text2.getText());
...

private static double getDoubleValue(String input) {

    double result = 0d;

    if ((input == null) || input.trim().isEmpty()) {
        return result;
    }

    try {
        result = Double.parseDouble(input);
    }
    catch (NumberFormatException ex) {
        // return result -or-
        // rethrow the exception -or-
        // whatever the application logic says
    }

    return result;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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