Codiqo

Learn Java · lesson 47 of 61 · about 10 minutes

Capstone: Core Logic

Add ticking off, listing and orders to the duty board.

What you'll learn

  • Replace items in a list
  • Sort with a Comparator
  • Process typed commands

Orders for the board

Now the staff give the board orders until done: tick 2 ticks off duty number 2, and list shows what's left, most urgent first. The rules live in DutyBoard. complete(number) throws for a number that isn't on the board or a duty that's already done, and otherwise swaps in markDone()'s copy with set and returns it. pending() keeps the duties that aren't done and sorts them by priority, then by title, with a Comparator. Main runs each order through an arrow switch, inside a try that catches a missing number first and any other rule after.

Rules as methods

  • complete(index) replaces the task with a done copy, and throws for a bad index
  • pending() returns the tasks not done, most urgent first
  • main reads commands such as add 1 Feed Phoebe, done 0 and list with an arrow switch

The core

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

record Task(String title, int priority, boolean done) {}

class TaskList {
    private final List<Task> tasks = new ArrayList<>();

    void add(String title, int priority) {
        tasks.add(new Task(title, priority, false));
    }

    void complete(int index) {
        if (index < 0 || index >= tasks.size()) throw new IllegalArgumentException("no task " + index);
        Task t = tasks.get(index);
        tasks.set(index, new Task(t.title(), t.priority(), true));
    }

    List<Task> pending() {
        List<Task> out = new ArrayList<>();
        for (Task t : tasks) if (!t.done()) out.add(t);
        out.sort(Comparator.comparingInt(Task::priority).thenComparing(Task::title));
        return out;
    }
}

public class Main {
    public static void main(String[] args) {
        TaskList list = new TaskList();
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String[] parts = in.nextLine().split(" ", 3);
            try {
                switch (parts[0]) {
                    case "add" -> list.add(parts[2], Integer.parseInt(parts[1]));
                    case "done" -> list.complete(Integer.parseInt(parts[1]));
                    case "list" -> list.pending().forEach(t -> System.out.println("P" + t.priority() + " " + t.title()));
                    default -> System.out.println("unknown: " + parts[0]);
                }
            } catch (IllegalArgumentException e) {
                System.out.println("error: " + e.getMessage());
            }
        }
    }
}

Output

error: no task 9
P2 Write capstone
P3 Tidy desk

Tip

split(" ", 3) splits into at most 3 parts, so a title with spaces stays together in parts[2].

Numbers people use

The board numbers its duties from 1, the way the staff count them, so complete() turns a number into an index with number - 1 and refuses anything below 1 or above size(). Inside the switch, each case with more than one statement gets braces, case "tick" -> { ... }, and nothing falls through to the next case.

Swapping in a new record

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

record Duty(String title, boolean done) {}

public class Main {
    public static void main(String[] args) {
        List<Duty> duties = new ArrayList<>(List.of(new Duty("Count the till", false), new Duty("Lock up", false)));
        int number = 2;
        Duty old = duties.get(number - 1);
        duties.set(number - 1, new Duty(old.title(), true));
        System.out.println(duties.get(1).done() + " " + duties.size());
    }
}

Output

true 2

Now try it yourself

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