Checking for empty String for error checking-Collection of common programming errors

There are multiple possibilities where a runtime error can occur in calculateHours():

  • hourArray is null and throws a NullPointerException
  • any hourArray[i] is null and throws a NullPointerException
  • hourArray[i].getText() can not be parsed to a Double and throws a NumberFormatException
  • Your hourArray might contains of less than 7 elements, which throws an IndexOutOfBoundsException

Beside that, hourArray[i].getText() != "" is a bad comparison because it does not check null and checks if the two objects are the same object, not if they are equal.

In addition, I guess you want to have sum += hour inside the loop, otherwise sum will contain the last value of the hourArray.

So, your method should look like this:

public String calculateHours (){
    double sum = 0;
    if(hourArray != null){ // hourArray might be null
        double hour = 0;
        for (int i = 0; i < hourArray.length; i++) { // use .length here
            // check for nulls and empty String
            if (hourArray[i] != null && hourArray[i].getText() != null 
                                     && !"".equals(hourArray[i].getText())) {
                try{ // the text might can not be parsed to a double
                    hour = Double.parseDouble(hourArray[i].getText());
                }catch(NumberFormatException ex){
                    hour = 0;
                }
            }
            else  {
                hour = 0;
            }
            sum += hour; // I guess you want that inside your loop
        }
    }
    return String.format("%.2f", sum);
}

Anyway, it would be better if this class is written in a way that it does not have to check for all this possibilities in the calculateHours() method. You notice how hard it becomes to read if all these checks must be done here.