Java
Putting it together
Write a CLI app with a menu loop.
Putting it together: command loop
In the last step we will combine all pieces into a command loop. Commands come as a String[]; each is either add:X, list, or done:N.
for (String cmd : commands) {
if (cmd.startsWith("add:")) {
list.addTask(cmd.substring(4));
} else if (cmd.equals("list")) {
list.listTasks();
} else if (cmd.startsWith("done:")) {
int idx = Integer.parseInt(cmd.substring(5));
list.completeTask(idx);
}
}
With substring(4) we extract the title and with Integer.parseInt the index. This is the skeleton of a real menu loop; reading user input will come later.
Integrating the project
In this lesson we brought all methods (Task, TodoList, addTask, listTasks, completeTask) together. The command loop runs over an array that simulates user input.
In a real CLI app, commands are read from String[] args or Scanner. You will see Scanner in the next group; then you can wire this skeleton to live user input.
Now we ask you to write this loop: process commands in order, routing each to the right method.
Exercise Write the command loop
Walk the commands array in main with for-each. For each command: if add:X call list.addTask(cmd.substring(4)), if list call list.listTasks(), if done:N call list.completeTask(Integer.parseInt(cmd.substring(5))).
Show example solution
for (String cmd : commands) {
if (cmd.startsWith("add:")) {
list.addTask(cmd.substring(4));
} else if (cmd.equals("list")) {
list.listTasks();
} else if (cmd.startsWith("done:")) {
int idx = Integer.parseInt(cmd.substring(5));
list.completeTask(idx);
}
}
Test yourself
-
Fill in the blank: detect the command type
if (cmd.____("add:")) {
list.addTask(cmd.substring(4));
}
Show answer
if (cmd.startsWith("add:")) {
list.addTask(cmd.substring(4));
}
-
What does Integer.parseInt(cmd.substring(5)) do?
- Throws an error
- Removes the "done:" prefix
- Divides cmd by 5
- Extracts the number 0 from "done:0"
Show answer
Extracts the number 0 from "done:0" — substring(5) gives "0", parseInt turns it into an int.
-
Match command to action
- add:Shopping
- Add a new task
- list
- Print the tasks
- done:0
- Complete the first task
- done:1
- Complete the second task
Next lesson: StringBuilder