babyDev - 1 year ago 72

Java Question

I'm taking a course in Java and we haven't officially learned if statements yet. I was studying and saw this question:

Write a method called pay that accepts two parameters: a real number for a TA's salary, and an integer for the number hours the TA worked this week. The method should return how much money to pay the TA. For example, the call pay(5.50, 6) should return 33.0. The TA should receive "overtime" pay of 1.5 times the normal salary for any hours above 8. For example, the call pay(4.00, 11) should return (4.00 * 8) + (6.00 * 3) or 50.0.

How do you solve this without using if statements? So far I've got this but I'm stuck on regular pay:

`public static double pay (double salary, int hours) {`

double pay = 0;

for (int i = hours; i > 8; i --) {

pay += (salary * 1.5);

}

}

Answer Source

To avoid direct use of flow control statements like `if`

or `while`

you can use `Math.min`

and `Math.max`

. For this particular problem using a loop would not be efficient either.

They may technically use an if statements or the equivalent, but so do a lot of your other standard library calls you already make:

```
public static double pay (double salary, int hours) {
int hoursWorkedRegularTime = Math.min(8, hours);
int hoursWorkedOverTime = Math.max(0, hours - 8);
return (hoursWorkedRegularTime * salary) +
(hoursWorkedOverTime * (salary * 1.5));
}
```