CodeBlanks Logo Icon CodeBlanks

Listing tasks

Print tasks with listTasks.

Listing tasks: listTasks

Now we will add a method to TodoList that prints tasks in a readable form: listTasks. This method prints each task on its own line.

void listTasks() {
  for (Task t : tasks) {
    System.out.println(t);
  }
}

The for-each loop puts each Task from the list into the t variable in turn. println(t) then calls the toString method and prints a readable line like [ ] Shopping.

Empty list case

When the list is empty, listTasks prints nothing; the for-each loop runs zero times. This silent behavior is usually what we want.

TodoList empty = new TodoList();
empty.listTasks();
// (the call ends without printing anything)

If you wish, you can print a notice at the top with if (tasks.isEmpty()). For now we keep it simple; you can customize this later.

Practice Write the listTasks method

Inside the TodoList class, define void listTasks(); the body should walk with for (Task t : tasks) and print each task with System.out.println(t). In main, add two tasks and call list.listTasks().

Starter code

Main.java
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    TodoList list = new TodoList();
    list.addTask("Shopping");
    list.addTask("Homework");
    // List the tasks
  }
}

class Task {
  String title;
  boolean done;
  Task(String title) {
    this.title = title;
    this.done = false;
  }
  public String toString() {
    return (done ? "[x] " : "[ ] ") + title;
  }
}

class TodoList {
  ArrayList<Task> tasks = new ArrayList<>();
  void addTask(String title) {
    tasks.add(new Task(title));
  }
  // Define the listTasks method: print each task on its own line
}

Sample solution

Main.java
// inside TodoList:
void listTasks() {
  for (Task t : tasks) {
    System.out.println(t);
  }
}
// inside main:
list.listTasks();

Expected output

[ ] Shopping
[ ] Homework

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match part to purpose

Term Meaning
for (Task t : tasks) Walks the list
println(t) Prints the task
toString Turns the task into text
tasks The list of all tasks

2 What does listTasks do when the list is empty?

  • It prints nothing
  • It prints null Correct answer
  • It throws an error
  • It prints an empty line

Explanation: For-each runs zero times on an empty list.

3 Fill in the blank: listTasks loop

Question
void listTasks() {
  for (Task t : ____) {
    System.out.println(t);
  }
}
Answer
void listTasks() {
  for (Task t : tasks) {
    System.out.println(t);
  }
}

Explanation: for (Task t : tasks) walks the list.

All lessons in Beginner