Use an if/else to decide whether to charge shipping based on a free-shipping threshold.
You start with:
int subtotal = 75;
int shipping_cost = 10;
int free_shipping_threshold = 100;
Build:
Subtotal: $75 Shipping: $10 Total: $85
Rules:
- If
subtotal >= free_shipping_threshold, setshippingto0; otherwise set it toshipping_cost. total = subtotal + shipping.- Always include all three lines (
Subtotal,Shipping,Total). When shipping is free, the line shows$0: for a subtotal of 120 the lines would beSubtotal: $120,Shipping: $0,Total: $120. - Join the three lines with a newline
"\n"into one stringresult, then print it withSystem.out.println(result).
Decide
shipping in an if/else first, then build the three lines.
Declare
int shipping; before the if, so it is still visible after the if/else, then assign it in both branches.
In Java
"Total: $" + total converts the number to text for you.
int subtotal = 75;
int shipping_cost = 10;
int free_shipping_threshold = 100;
int shipping;
if (subtotal >= free_shipping_threshold) {
shipping = 0;
} else {
shipping = shipping_cost;
}
int total = subtotal + shipping;
String line1 = "Subtotal: $" + subtotal;
String line2 = "Shipping: $" + shipping;
String line3 = "Total: $" + total;
String result = line1 + "\n" + line2 + "\n" + line3;
System.out.println(result);
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
