I just started to learn Java. There is a course in MIT and there is an assignment to write a class for pay calculation. Part of the task is:
- The base pay must not be less than the minimum wage ($8.00 an hour). If it is, print an error.
- If the number of hours is greater than 60, print an error message.
The code I have written is as follows:
public class fooCorporation {
private float totalPay;
private float calc;
public float totalPay(double basePay, int hours){
if(hours <= 40){
totalPay = (float) (basePay * hours);
}
else if(hours > 40){
int extraHours = hours - 40;
float payForFortyHours = (float) (basePay * hours);
float payForextraHours = (float) (basePay * 1.5 * extraHours);
totalPay = payForFortyHours + payForextraHours;
}
return totalPay;
}
public static void main(String[] args){
fooCorporation foo = new fooCorporation();
System.out.println("employee 1: " + foo.totalPay(7.50,35));
System.out.println("employee 2: " + foo.totalPay(8.20,47));
System.out.println("employee 3: " + foo.totalPay(10.00,73));
}
}
The problem I am facing is how to print an error message from the function totalPay() when some conditions are not met. Can the above logic be written in a different way?
You generally don’t print things in the middle of general purpose functions since (1) it’s annoying to the people using those functions; and (2) it gives no indication of a problem to the calling code.
Usually, you would either throw an exception or have some specific return code indicating an error condition.
Then the caller can decide what to print (or do otherwise if printing is not appropriate).
For example, if you can determine that the total pay should always be positive, just return
-1.0for an error condition. For example:That method of yours, by the way, gives you double time and a half (
x2.5) for overtime since you’re not adjusting the base hours down to 40. Make sure that’s what you want rather than time and a half (x1.5).