Learn Java · lesson 9 of 61 · about 9 minutes
Project: Group Booking
Sell a group booking with a discount: read the percentage off, work out the price in whole cents, and print it with printf.
What you'll learn
- Combine Scanner, arithmetic and printf
- Work out a percentage in whole cents
- Format money to two decimals
The plan
Groups get a discount. The desk will:
1. Read the percentage off
2. Count the tickets: the 4 already sold plus the extra seats
3. Work out the price in whole cents
4. Print it as dollars and cents with printf
A percentage in cents
To take 10% off, pay 90% of the price: total * (100 - discount) / 100. Multiply first, then divide.
Doing it the other way round, total * (discount / 100), divides two ints first: 10 / 100 is 0, so nobody ever saves anything.
To print cents as money, %d.%02d prints the dollars, a dot, then the cents with at least two digits, so 5 cents shows as 05. %% prints a percent sign.
A group price
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int tickets = in.nextInt();
int discount = in.nextInt();
int full = tickets * 1235;
int paid = full * (100 - discount) / 100;
System.out.printf("%d tickets: $%d.%02d%n", tickets, full / 100, full % 100);
System.out.printf("With %d%% off: $%d.%02d%n", discount, paid / 100, paid % 100);
System.out.printf("You save: $%d.%02d%n", (full - paid) / 100, (full - paid) % 100);
}
}Output
5 tickets: $61.75
With 20% off: $49.40
You save: $12.35Tip
Integer division drops the cents left over, so a price can be a cent lower than the exact one. Banks and shops decide which way to round; here, the customer gets the cent.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.