Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a decision without an if statement

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);      } } 
like image 706
babyDev Avatar asked Aug 31 '16 21:08

babyDev


People also ask

How do you write codes without an if statement?

i.e. you could just as easily write bool isSmall = i < 10; - it's this that avoids the if statement, not the separate function. Code of the form if (test) { x = true; } else { x = false; } or if (test) { return true; } else { return false; } is always silly; just use x = test or return test .

What if there is no condition in if statement?

A condition need not necessarily contain comparators such as == or < etc. A condition can be any expression. Now, if the if expression evaluates to a zero value it is considered false and the if statement is not evaluated. Otherwise, it is considered true and the if statement is evaluated.


Video Answer


2 Answers

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)); } 
like image 147
NESPowerGlove Avatar answered Sep 22 '22 00:09

NESPowerGlove


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.

like image 34
js441 Avatar answered Sep 24 '22 00:09

js441