Challenge: To-Do List
Completed
Keep a to-do list in an ArrayList<String>. Read n commands:
add <task>– add the task (one word) at the enddone <task>– remove that task, if it's there
At the end, print the number of tasks left and then each task on its own line, numbered from 1.
Input
First n, then n commands.
Output
Tasks left: <count> 1. <task> ...
Example
Input
4 add shop add cook add clean done cook
Output
Tasks left: 2 1. shop 2. clean
Editor
Java
Hints
list.remove("word") removes by value and does nothing if it isn't there.
Use a normal for loop with i so you can print the number i + 1.
Solution explanation
The list grows with add and shrinks with remove, and keeps the order tasks were added.
Show solution
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<String> todo = new ArrayList<>();
for (int i = 0; i < n; i++) {
String cmd = sc.next();
String task = sc.next();
if (cmd.equals("add")) {
todo.add(task);
} else {
todo.remove(task);
}
}
System.out.println("Tasks left: " + todo.size());
for (int i = 0; i < todo.size(); i++) {
System.out.println((i + 1) + ". " + todo.get(i));
}
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module