Codiqo

Learn Java · lesson 25 of 61 · about 10 minutes

Project: Ticket Prices

End the visit with a price list by age, built from small methods that each do one job, and say which ticket the customer's age gets.

What you'll learn

  • Split work into methods
  • Loop and call methods
  • Format a table with printf

A price list

The desk already sorts ages into child, adult and senior tickets. A price list makes those limits easy to see: a row for ages 8, 28, 48, 68 and 88 with the ticket type and its price, and a last line saying which ticket this customer's age gets. Every part is a small method with one job, and main only loops and calls.

One job per method

  • ticketType(age) picks the type, catching ages that aren't real first
  • ticketPrice(type) gives the price of that type in cents
  • printRow(age) prints one line, using money for the price
  • main loops from 8 to 88 in steps of 20

The price list

public class Main {
    public static void main(String[] args) {
        System.out.println("  Age | Ticket | Price");
        for (int a = 8; a <= 88; a += 20) {
            printRow(a);
        }
    }

    // an amount in cents, shown as dollars
    static String money(int cents) {
        return String.format("$%d.%02d", cents / 100, cents % 100);
    }

    // the ticket type for an age, with the same limits as the desk
    static String ticketType(int age) {
        if (age < 0 || age > 120) return "None";
        if (age < 12) return "Child";
        if (age < 65) return "Adult";
        return "Senior";
    }

    // the price of one ticket of that type, in cents
    static int ticketPrice(String type) {
        return switch (type) {
            case "Child" -> 800;
            case "Senior" -> 900;
            default -> 1235;
        };
    }

    // one row of the price list
    static void printRow(int age) {
        String type = ticketType(age);
        System.out.printf("%5d | %-6s | %s%n", age, type, money(ticketPrice(type)));
    }
}

Output

  Age | Ticket | Price
    8 | Child  | $8.00
   28 | Adult  | $12.35
   48 | Adult  | $12.35
   68 | Senior | $9.00
   88 | Senior | $9.00

Tip

%-6s pads the text to 6 characters on the right, so the column after it lines up whatever the word is.

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.