Codiqo

Learn Java · lesson 45 of 61 · about 10 minutes

Project: Private Hire

Take the private hire bookings: build classes behind an interface, refuse bad sizes with exceptions, and print a sorted report.

What you'll learn

  • Implement an interface in several classes
  • Validate in constructors
  • Sort with a Comparator

Private hire

The cinema hires out its screens: a kids' party costs $8 a child, and a corporate booking $90 an hour. Every booking is a Hire, an interface with cost() and label(), kept by Party and Corporate. Their constructors throw IllegalArgumentException for a party with no children or a booking outside 1 to 8 hours, so a bad booking is never made. The manager types bookings like party 6 until done, and the desk lists them from dearest to cheapest with a total.

The plan

  • Shape is an interface with area() and name()
  • Rectangle and Circle implement it and throw IllegalArgumentException for sizes that aren't positive
  • main reads lines like rect 3 4, skips invalid shapes and prints them sorted by area

The shape report

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

interface Shape {
    double area();
    String name();
}

class Rectangle implements Shape {
    private final double w, h;
    Rectangle(double w, double h) {
        if (w <= 0 || h <= 0) throw new IllegalArgumentException("rectangle sides must be positive");
        this.w = w;
        this.h = h;
    }
    public double area() { return w * h; }
    public String name() { return "rectangle"; }
}

class Circle implements Shape {
    private final double r;
    Circle(double r) {
        if (r <= 0) throw new IllegalArgumentException("circle radius must be positive");
        this.r = r;
    }
    public double area() { return Math.PI * r * r; }
    public String name() { return "circle"; }
}

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        List<Shape> shapes = new ArrayList<>();
        while (in.hasNext()) {
            String kind = in.next();
            try {
                if (kind.equals("rect")) shapes.add(new Rectangle(in.nextDouble(), in.nextDouble()));
                else if (kind.equals("circle")) shapes.add(new Circle(in.nextDouble()));
            } catch (IllegalArgumentException e) {
                System.out.println("skipped: " + e.getMessage());
            }
        }
        shapes.sort(Comparator.comparingDouble(Shape::area).reversed());
        for (Shape s : shapes) System.out.printf("%-10s%.2f%n", s.name(), s.area());
    }
}

Output

skipped: rectangle sides must be positive
circle    12.57
rectangle 12.00
circle    3.14

Tip

Comparator.comparingDouble(Shape::area).reversed() reads almost like English: compare shapes by area, biggest first.

Ties keep their order

list.sort(...) is stable: items the comparator calls equal stay in the order they were added. So two bookings that cost the same are listed in the order the manager typed them, and the report comes out the same every time.

Longest first, ties as they were

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> films = new ArrayList<>(List.of("Up", "Jaws", "Moon", "It"));
        films.sort(Comparator.comparingInt(String::length).reversed());
        System.out.println(films);
    }
}

Output

[Jaws, Moon, Up, It]

Now try it yourself

This lesson is free in Codiqo, with 9 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.