Search code examples
javajtextfield

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

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


Solution

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