Checking for empty String for error checking-Collection of common programming errors
There are multiple possibilities where a runtime error can occur in calculateHours():
hourArrayisnulland throws aNullPointerException- any
hourArray[i]is null and throws aNullPointerException hourArray[i].getText()can not be parsed to aDoubleand throws aNumberFormatException- Your
hourArraymight contains of less than 7 elements, which throws anIndexOutOfBoundsException
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.