Project: The Menu
Talk to the user.
The last piece is the menu. It reads commands from the user, and calls the right TaskList method for each one.
- Read commands
- Call TaskList
- Loop until quit
Menu.java
One Scanner reads the keyboard. Run loops forever, asking for a command. Quit leaves the method, with return. A switch picks what to do. Add asks for a title, and uses priority two. Done asks for an id. List prints every task. And anything else gets a friendly message. Ask prints a question, and reads the answer.
import java.util.Scanner;
public class Menu {
private static final Scanner in = new Scanner(System.in);
public static void run(TaskList list) {
while (true) {
String cmd = ask("add, done, list or quit: ");
if (cmd.equals("quit")) return;
switch (cmd) {
case "add" -> list.add(ask("Title: "), 2);
case "done" -> list.complete(Integer.parseInt(ask("Id: ")));
case "list" -> list.all().forEach(System.out::println);
default -> System.out.println("Unknown command: " + cmd);
}
}
}
static String ask(String q) { System.out.print(q); return in.nextLine(); }
}The whole program
Main loads, runs the menu, and saves. Run it. We add a task, and type a wrong command by mistake. Then we complete task one, list everything, and quit. Six tasks are saved, ready for next time.
public class Main {
public static void main(String[] args) throws Exception {
TaskStore store = new TaskStore("tasks.txt");
TaskList list = new TaskList();
store.load().forEach(list::restore);
Menu.run(list);
store.save(list.all());
System.out.println("Saved " + list.all().size() + " tasks. Bye!");
}
}add, done, list or quit: add Title: Call mum add, done, list or quit: remove Unknown command: remove add, done, list or quit: done Id: 1 add, done, list or quit: list 1 [x] !!! Pay rent 2 [x] ! Water plants 3 [ ] !! Book dentist; maybe Friday 4 [x] !! Email Sam 5 [ ] !!! Finish report 6 [ ] !! Call mum add, done, list or quit: quit Saved 6 tasks. Bye!
Also uses Task.java
public record Task(int id, String title, int priority, boolean done) {
public Task {
if (title.isBlank()) throw new IllegalArgumentException("Title can't be empty");
if (priority < 1 || priority > 3) throw new IllegalArgumentException("1-3 only");
}
public Task complete() {
return new Task(id, title, priority, true);
}
@Override
public String toString() {
String box = done ? "[x]" : "[ ]";
return String.format("%2d %s %-3s %s", id, box, "!".repeat(priority), title);
}
}Also uses TaskList.java
import java.util.*;
public class TaskList {
private final List<Task> tasks = new ArrayList<>();
private int nextId = 1;
public Task add(String title, int priority) {
Task t = new Task(nextId++, title, priority, false);
tasks.add(t);
return t;
}
public void complete(int id) {
tasks.replaceAll(t -> t.id() == id ? t.complete() : t);
}
public boolean remove(int id) { return tasks.removeIf(t -> t.id() == id); }
public List<Task> all() { return List.copyOf(tasks); }
public void restore(Task t) { tasks.add(t); nextId = Math.max(nextId, t.id() + 1); }
}Also uses TaskStore.java
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
public class TaskStore {
private final Path file;
public TaskStore(String name) { file = Path.of(name); }
public void save(List<Task> tasks) throws IOException {
List<String> lines = new ArrayList<>();
for (Task t : tasks) {
lines.add(t.id() + ";" + t.priority() + ";" + t.done() + ";" + t.title());
}
Files.write(file, lines);
}
public List<Task> load() throws IOException {
List<Task> out = new ArrayList<>();
if (!Files.exists(file)) return out;
for (String line : Files.readAllLines(file)) {
String[] p = line.split(";", 4);
int id = Integer.parseInt(p[0]), prio = Integer.parseInt(p[1]);
out.add(new Task(id, p[3], prio, Boolean.parseBoolean(p[2])));
}
return out;
}
}Also uses Menu.java
import java.util.Scanner;
public class Menu {
private static final Scanner in = new Scanner(System.in);
public static void run(TaskList list) {
while (true) {
String cmd = ask("add, done, list or quit: ");
if (cmd.equals("quit")) return;
switch (cmd) {
case "add" -> list.add(ask("Title: "), 2);
case "done" -> list.complete(Integer.parseInt(ask("Id: ")));
case "list" -> list.all().forEach(System.out::println);
default -> System.out.println("Unknown command: " + cmd);
}
}
}
static String ask(String q) { System.out.print(q); return in.nextLine(); }
}Also uses tasks.txt
1;3;false;Pay rent
2;1;true;Water plants
3;2;false;Book dentist; maybe Friday
4;2;true;Email Sam
5;3;false;Finish reportIdeas to extend it
Here are some ideas, to keep practising. Add a remove command. Ask for a priority, and check the input. Add due dates, with local date. And sort the list by priority, with a comparator.
| key | value |
|---|---|
| remove | list.remove(id) |
| priority | ask, then validate |
| due dates | LocalDate |
| sorting | Comparator |
Summary
The menu reads commands, and calls TaskList. Main ties loading, the menu, and saving together. Our project is complete! Next, where to go from here.
Key takeaways- Scanner + switch
- Main ties it together
- A real program