How to make a decision without an if statement

Published on Author Code Father

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?

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

     double pay = 0;

     for (int i = hours; i >8;  i --) {
         pay += (salary * 1.5);}}

Since you’ve used a for loop, here’s a solution just using two for loops.

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

    double pay = 0;

    for (int i = 0; i < hours && i < 8; i++) {
        pay += salary;}
    
    for (int i = 8; i < hours; i++) {
        pay += (salary * 1.5);}
    

    return pay;}

This sums the salary for the regular hours up to 8, and then sums the salary for the overtime hours, where the overtime hours are paid at 1.5 * salary.

If there are no overtime hours, the second for loop will not be entered and will have no effect.

Comments

comments