- We would like to assess a service charge for cashing a check. Th service charge depends on the amount of the check. If the check amount is less than 10$, we will charge 1$. If the amount is greater than 10$ but less than 100$, we will charge 10% of the amount. If the amount is greater than 100$, but less than 1,000$, we will charge 5$ plus 5% of the amount. If the value is over 1,000$, we will charge 40$ plus 1% of the amount. Use a multibranch/nested if-else statement to compute for the service charge.
tried writing source code but failed.
CodePudding user response:
I think it will look like this. I put the amount randomly.
int amount = 500;
double pay = 0;
if(amount > 1000){
pay = 40 (amount*0.01);
} else if(amount > 100 && amount < 1000){
pay = 5 (amount*0.05);
} else if(amount > 10 && amount < 100){
pay = amount*0.1;
} else if(amount < 10){
pay = 1;
}
System.out.println(pay "$")
CodePudding user response:
public double getCharge(int check_amount) {
if (check_amount < 10) {
return 1;
} else if (check_amount < 100) {
return 0.1 * check_amount;
} else if (check_amount < 1000) {
return 5 0.05 * check_amount;
} else if (check_amount > 1000) {
return 40 0.01 * check_amount;
}
return 0;
}
If we start with the lowest condition, we can neglect to have two conditions in the if statement.
In the main:
public static void main(String[] args) {
System.out.println(getCharge(9)) //when value is less than 10
System.out.println(getCharge(90)) //when value is less than 100
System.out.println(getCharge(900)) //when value is less than 1000
System.out.println(getCharge(5000)) //when value is greater than 1000
}
Output:
1
9
50
90
CodePudding user response:
The question asks for nested if statements, so this code may fair better:
public double getCharge(int check_amount) {
if (check_amount < 1000){
if (check_amount < 100){
if (check_amount <10){
return 1;
}else {
return 0.1*check_amount;
}
} else {
return 5 0.05*check_amount;
}
} else {
return 40 0.01*check_amount;
}
}
This has the same function as the previous code i posted but as nested if-else statements as per request.