From 9ef736609b6ef98396c96500b68aa1eb5b089b0e Mon Sep 17 00:00:00 2001 From: shunjieee Date: Thu, 29 Feb 2024 19:11:27 +0800 Subject: [PATCH] Add sort command Allow user to sort the list base on the task's completion status. Let's * add SortCommand.java * update Parser.java to include "sort" --- src/main/java/command/SortCommand.java | 58 ++++++++++++++++++++++++++ src/main/java/common/Parser.java | 7 +++- 2 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 src/main/java/command/SortCommand.java diff --git a/src/main/java/command/SortCommand.java b/src/main/java/command/SortCommand.java new file mode 100644 index 0000000000..92011fd082 --- /dev/null +++ b/src/main/java/command/SortCommand.java @@ -0,0 +1,58 @@ +package command; + +import java.util.Comparator; + +import task.Task; +import task.TaskList; + +/** + * {@inheritDocs} + * Sort the tasks in the task list. + */ +public class SortCommand extends Command { + private TaskList taskList; + + /** + * Creates an instance of SortCommand. + */ + public SortCommand(TaskList taskList) { + this.taskList = taskList; + } + + /** + * {@inheritDocs} + * List all the tasks in the task list. + */ + @Override + public String execute() { + taskList.getList().sort(new StatusComparator()); + String message = "I have sorted the task list according to the tasks' statuses."; + return message + "\n\n" + new ListCommand(taskList).execute(); + } + + /** + * {@inheritDoc} + * + * @return True if program will exit. + */ + @Override + public boolean isExit() { + return false; + } + + static class StatusComparator implements Comparator { + // undone status are on top of the list + @Override + public int compare(Task task1, Task task2) { + if (!task1.checkStatus() && task2.checkStatus()) { + return -1; + + } else if (task1.checkStatus() && !task2.checkStatus()) { + return 1; + + } else { + return task1.getTaskName().compareToIgnoreCase(task2.getTaskName()); + } + } + } +} diff --git a/src/main/java/common/Parser.java b/src/main/java/common/Parser.java index 298bcad57e..85bb004631 100644 --- a/src/main/java/common/Parser.java +++ b/src/main/java/common/Parser.java @@ -10,6 +10,7 @@ import command.FindCommand; import command.ListCommand; import command.MarkCommand; +import command.SortCommand; import command.UnmarkCommand; import task.TaskList; @@ -76,12 +77,16 @@ public Command parse() throws IndexOutOfBoundsException, NumberFormatException, cmd = new FindCommand(tasks, st); return cmd; + case "sort": + cmd = new SortCommand(tasks); + return cmd; + case "bye": cmd = new ExitCommand(); return cmd; default: - throw new DukeException("OOPS!! Pls try again. :)"); + throw new DukeException("OOPS!! Pls try again, hustler. :)"); } } }