Java netbeans - 如果jtextfield值为空,如何将jtextfield值指定为零

问题描述 投票:0回答:2
    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值分配给零。

java jtextfield
2个回答
1
投票

您可以使用此方法而不是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);

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.