0
    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);

I want to assign double B,C,E,F values to zero when the jtextfield is empty.

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Dalvik
  • 3
  • 2
  • Make use of a [Ternary Operator](https://www.tutorialspoint.com/Java-Ternary-Operator-Examples), for example: `double B = Double.parseDouble((emp_txt2.getText().equals("") ? "0" : emp_txt2.getText()));`. – DevilsHnd - 退職した Sep 06 '18 at 08:09

2 Answers2

1

You could use this method instead of 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;
     }  
}

And then to:

double F = tryParsDouble(wop_txt5.getText(), 0.0);
Ace of Spade
  • 388
  • 3
  • 22
0

Try entering the values in the emp_text2 text field and the code returns the following values respectively: "", " ", "1", "1.1", "-1.1", "1.0 " returns 0.0, 0.0, 1.0, 1.1, -1.1, 1.0.

What happens if the input is "1.1x" ? This throws NumberFormatException - and the application needs to figure what to do.

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;
}
prasad_
  • 12,755
  • 2
  • 24
  • 36