CodeBlanks Logo Icon CodeBlanks

Completing tasks

Update status with completeTask.

Completing tasks: completeTask

Now we will add a completeTask(int index) method that marks a task as completed. This method sets the done field of the task at the given index to true.

void completeTask(int index) {
  tasks.get(index).done = true;
}

Here tasks.get(index) fetches the Task object at that index, then .done = true updates its state. Because the object reference stays the same, the change is permanent on the task in the list.

Invalid index hazard

If you pass an index that is not in the list to completeTask, tasks.get(index) throws an IndexOutOfBoundsException. To prevent this, you can add a bounds check at the top of the method.

void completeTask(int index) {
  if (index < 0 || index >= tasks.size()) return;
  tasks.get(index).done = true;
}

For now we do not add this check; but in a real app, always validating an index that comes from the user is good practice.

Practice Write the completeTask method

Inside TodoList, define void completeTask(int index); the body should run tasks.get(index).done = true. In main, add two tasks, call list.completeTask(0), and print with 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");
    // Mark the first task as completed
    // 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));
  }
  void listTasks() {
    for (Task t : tasks) {
      System.out.println(t);
    }
  }
  // Define completeTask(int index): mark the task at that index as done
}

Sample solution

Main.java
// inside TodoList:
void completeTask(int index) {
  tasks.get(index).done = true;
}
// inside main:
list.completeTask(0);
list.listTasks();

Expected output

[x] Shopping
[ ] Homework

Questions and answers

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

1 What does tasks.get(0) return?

  • The first Task object
  • The title of the first task
  • boolean done Correct answer
  • The index 0

Explanation: get(0) returns the first Task object itself.

2 Match call to meaning

Term Meaning
tasks.get(0) First task object
tasks.get(0).done = true Complete the first task
tasks.size() Number of tasks
tasks.add(new Task(...)) Add a new task

3 Fill in the blank: complete the task

Question
void completeTask(int index) {
  tasks.____(index).done = true;
}
Answer
void completeTask(int index) {
  tasks.get(index).done = true;
}

Explanation: tasks.get(index).done = true completes the task.

All lessons in Beginner