patternjavaModerate
Calculate someone's pay, including overtime
Viewed 0 times
overtimesomeonepayincludingcalculate
Problem
In this problem, you need to calculate someone's pay by multiplying their salary (double)by the hours (int) worked. If they worked for more than 8 hours, you pay them 1.5 times their salary for however many hours more they worked.
Here is my solution.
Wondering if there is any way to do it without if else statements since the course hasn't taught those yet.
Here is my solution.
public static double pay(double a, int b) {
if (b > 8) {
return (a * 8) + ((b - 8)*(a * 1.5));
}
else {
return (a * b);
}}Wondering if there is any way to do it without if else statements since the course hasn't taught those yet.
Solution
You should use better variable names, for a start.... consider:
Then, your code is not that bad (with some indentation fixes too):
There is no good way to handle the overtime rate other than with a conditional somewhere. Ternary conditions may help a bit.....
public static double pay(double hourlyWage, int hours) {
...
}Then, your code is not that bad (with some indentation fixes too):
public static double pay(double hourlyWage, int hours) {
if (hours > 8) {
return (hourlyWage * 8) + ((hours - 8)*(hourlyWage * 1.5));
}
else {
return (hourlyWage * hours);
}
}There is no good way to handle the overtime rate other than with a conditional somewhere. Ternary conditions may help a bit.....
public static double pay(double hourlyWage, int hours) {
int regular = hours > 8 ? 8 : hours;
int overtime = hours - regular;
return hourlyWage * (regular + (1.5 * overtime));
}Code Snippets
public static double pay(double hourlyWage, int hours) {
...
}public static double pay(double hourlyWage, int hours) {
if (hours > 8) {
return (hourlyWage * 8) + ((hours - 8)*(hourlyWage * 1.5));
}
else {
return (hourlyWage * hours);
}
}public static double pay(double hourlyWage, int hours) {
int regular = hours > 8 ? 8 : hours;
int overtime = hours - regular;
return hourlyWage * (regular + (1.5 * overtime));
}Context
StackExchange Code Review Q#106938, answer score: 11
Revisions (0)
No revisions yet.