Very new to programming. I would want the user to receive a 10% discount if he/she is over 60 (age>60) and 5% discount if he/she is between over 55 and equal to 60. (60<=age>55). I know that my code is completely wrong, but I would like to fix this step by step if possible.
import java.util.*;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int price, age;
double tax, payAmount;
double discountRate_56_to_60 = 0.05;
double discountRate_60_above = 0.1;
payAmount = price * tax;
System.out.print("Price?");
price = input.nextInt();
System.out.print("Tax(%)?");
tax = input.nextDouble();
System.out.print("Age?");
age = input.nextInt();
System.out.println("You pay: $");
payAmount = input.nextDouble();
if (age > 55) {
payAmount;
}
else if (age >= 60) {
payAmount;
}
}
}
You made a few mistakes:
The line payAmount = price * tax;
is executed too early. How can you calculate what the pay amount is before getting the price and tax from the user?
The line payAmount = input.nextDouble();
should not be there. The problem is supposed to output the payAmount
, not ask for it as an input.
payAmount
is not a statement.
Your if statements seem to be wrong. If an age is not greater than 55, it can never be greater than or equal to 60.
Here is the fixed code, corrections are written in comments:
Scanner input = new Scanner(System.in);
int price, age;
double tax, payAmount;
double discountRate_56_to_60 = 0.05;
double discountRate_60_above = 0.1;
System.out.print("Price?");
price = input.nextInt();
System.out.print("Tax(%)?");
tax = input.nextDouble();
payAmount = price * tax; // I moved the line here!
System.out.print("Age?");
age = input.nextInt();
// removed the line asking for pay amount
if (age > 60) { // first we check if age is greater than 60. If it is not, then we check if it is greater than 55.
// with a little analysis you will see that this is equivalent to the stated conditions
payAmount -= payAmount * discountRate_60_above; // calculate the payAmount by subtracting the pay amount times discount rate
}
else if (age > 55) {
payAmount -= payAmount * discountRate_56_to_60;
}
System.out.println("You pay: $" + payAmount); // finally output the payAmount
Try the below code
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int price, age;
double payAmount = 0;
System.out.print("Price?");
price = input.nextInt();
System.out.print("Age?");
age = input.nextInt();
if (age > 55 && age <= 60) {
payAmount = price - price * 5 / 100;
} else if (age > 60) {
payAmount = price - price * 10 / 100;
}
System.out.println("You pay: $ " + payAmount);
input.close();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With