public static double calculateMinPayment(double newBalance) {
double x;
if (newBalance < 0.00) {
return 0.00;
} else if (newBalance > 0.00 && newBalance <= 49.99) {
x = newBalance;
} else if (newBalance >= 50.00 && newBalance <= 300) {
x = 50.00;
} else {
x = newBalance * 0.2;
}
return x;
}
I'm not able to use the operators && or ||, how would I be able to format this same code without those operators?
CodePudding user response:
You can use Nested
if
statements like below:
public static double calculateMinPayment(double newBalance) {
double x;
if (newBalance < 0.00) {
return 0.00;
} else if (newBalance > 0.00) {
if (newBalance <= 49.99) {
x = newBalance;
} else if (newBalance >= 50.00) {
if (newBalance <= 300) {
x = 50.00;
} else {
x = newBalance * 0.2;
}
} else {
x = newBalance * 0.2;
}
} else {
x = newBalance * 0.2;
}
return x;
}
CodePudding user response:
Since your conditions are in increasing size and with no gaps you don't need any AND conditions and the comparison can be made quite straight forward.
public static double calculateMinPayment(double newBalance) {
double x;
if (newBalance < 0.00) {
return 0.00;
} else if (newBalance <= 49.99) {
return newBalance;
} else if (newBalance <= 300) {
return 50.00;
} else {
return newBalance * 0.2;
}
}
A small variation is to skip all the else
since we are using return
if (newBalance < 0.00) {
return 0.00;
}
if (newBalance <= 49.99) {
return newBalance;
}
if (newBalance <= 300) {
return 50.00;
}
return newBalance * 0.2;