The gross pay text field was suppose to be filled out as the user is filling out the salary and overtime textfield, but as soon as the program starts it always shows the java.lang.NumberFormatException: empty String error

Here is the code that use

   private void jTextGrossPayMouseEntered(java.awt.event.MouseEvent evt) {                                           
 try{

    DecimalFormat numberFormat = new DecimalFormat("#.00");

   double salary = Double.parseDouble(jTextBasicSalary.getText());
   double hours = Double.parseDouble(jTextHours.getText());     
    double overtime = Double.parseDouble(jTextOvertime.getText());     
    double overtimepay = Double.parseDouble(jTextOvertimePay.getText());     
   double total1;
   double total2;
  double total3;

   total1 = salary * hours;
    total2 = overtime * overtimepay;
   total3 = total1 + total2;

  String gross = String.valueOf(total3);

   jTextGrossPay.setText(gross);

   }                                          

     catch(Exception e){
      e.printStackTrace();
    }

   }

And after i run the program these are the errors

java.lang.NumberFormatException: empty String

2 Answers

1
GhostCat On Best Solutions

Here:

private void jTextGrossPayMouseEntered(

indicates that this code gets executed when a mouse enters some component on your screen.

You have to understand: a mouse moving somewhere is not the same as "the user has entered all required information in all text fields".

Then:

double salary = Double.parseDouble(jTextBasicSalary.getText());

What you could/should do: check the contents of your text fields before doing anything about their content!

Meaning: before even thinking about parsing, you should check if the text field contains a non-empty string. If so, you could then do that parsing within a try/catch block. And if parsing fails, you can show a message box to the user telling him what you expect him to enter. You should do that for all your text fields separately.

And as said initially: ask yourself when that checking/parsing should occur. Should it really happen when the mouse enters "something"? Or would it be more like: that should happen when some button gets clicked?

So: the solution might also be to write that new code, and put it into some sort of action listener. That reacts to actions, such as button clicks, or selection of a menu item!

0
springe On

you could implement something like a helper method that checks if the input is a valid Double:

private boolean checkValidInput(String input) {
    try {
        Double.parseDouble(input);
        return true;
    } catch (Exception e){
        System.out.println("input :" + input +" is not a valid double");
        return false;
    }
}

There might be faster implementations but this one is easy and works...