Why does this method result in a runtime error? I understand the calc wont work with an empty string, so I set hour to 0 if this is the case.
Call:
String hoursJLabel = actionObject.calculateHours();
totalHours.setText(hoursJLabel);
Method:
public String calculateHours (){
double sum = 0;
double hour = 0;
for (int i = 0; i < 7; i++) {
if (hourArray[i].getText() != "") {
hour = Double.parseDouble(hourArray[i].getText());
}
else {
hour = 0;
}
}
sum += hour;
return String.format("%.2f", sum);
}
There are multiple possibilities where a runtime error can occur in
calculateHours():hourArrayisnulland throws aNullPointerExceptionhourArray[i]is null and throws aNullPointerExceptionhourArray[i].getText()can not be parsed to aDoubleand throws aNumberFormatExceptionhourArraymight contains of less than 7 elements, which throws anIndexOutOfBoundsExceptionBeside that,
hourArray[i].getText() != ""is a bad comparison because it does not checknulland checks if the two objects are the same object, not if they are equal.In addition, I guess you want to have
sum += hourinside the loop, otherwisesumwill contain the last value of thehourArray.So, your method should look like this:
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.