diff --git a/src/main/java/CustomExceptions/DuplicateException.java b/src/main/java/CustomExceptions/DuplicateException.java index ffe506afb2..df9df95402 100644 --- a/src/main/java/CustomExceptions/DuplicateException.java +++ b/src/main/java/CustomExceptions/DuplicateException.java @@ -7,19 +7,19 @@ public class DuplicateException extends Exception { private String message; /** - * Adds the appropriate index to the Duplicate task message + * Adds the appropriate index to the Duplicate task message. * @param index index of the task with the clash */ public DuplicateException(int index) { - message = DUPLICATE_TASK + "Task: " + (index+1) + "\n"; + message = DUPLICATE_TASK + "Task: " + (index + 1) + "\n"; } /** - * toString() method returning the message of the Exception + * toString() method returning the message of the Exception. * @return the message of the Exception */ @Override - public String toString(){ + public String toString() { return LINE + message + LINE; } } diff --git a/src/main/java/CustomExceptions/RoomShareException.java b/src/main/java/CustomExceptions/RoomShareException.java index 40d9b71e72..1058897529 100644 --- a/src/main/java/CustomExceptions/RoomShareException.java +++ b/src/main/java/CustomExceptions/RoomShareException.java @@ -11,37 +11,42 @@ public class RoomShareException extends Exception { private static final String WRONG_FORMAT_TEXT = "\tWrong Format Detected\n"; private static final String WRONG_PRIORITY_TEXT = "\tYou've entered wrong format of priority\n"; private static final String SUB_TASK_TEXT = "\tOnly Assignments are supported with Subtasks\n"; - public static final String WRONG_TASK_TYPE_TEXT = "\tOnly meeting, assignment, or leave tag are accepted\n"; - public static final String EMPTY_DESCRIPTION_TEXT = "\tYou haven't included the description of you task\n"; - public static final String EMPTY_DATE_TEXT = "\tYou haven't included the date of your task\n"; - public static final String EMPTY_USER_TEXT = "\tYou haven't included the user of your task\n"; - public static final String EMPTY_TASK_TYPE_TEXT = "\tYou haven't specified the type of your task: assignment, meeting, or leave\n"; - public static final String WRITE_ERROR_TEXT = "\tError in writing file, cancelling write process...\n"; - public static final String WRONG_INDEX_FORMAT_TEXT = "\tThe index you've enter is in the wrong format\n"; - public static final String WRONG_TIME_FORMAT_TEXT = "\tYou've entered an invalid time format\n"; - public static final String WRONG_SORT_TYPE_TEXT = "\tPlease enter a valid sort type: priority, alphabetical or deadline\n"; - public static final String LOG_ERROR_TEXT = "\tError writing to a new log file. Please try again.\n"; - public static final String NEGATIVE_AMOUNT_TEXT = "\tThe amount of time cannot be negative.\n"; - public static final String EMPTY_SUB_TASK = "\tYou haven't included your list of sub-tasks\n"; - public static final String DUPLICATE_SUB = "\tDuplicate subtask detected\n"; - public static final String LEAVE_DONE = "\tLeave cannot be set to done\n"; - public static final String INVALID_INPUT_TEXT = "\tYour input String seems to be wrong.\n" - +"\tPlease check your formatting and ensure that the use of special characters are correct!\n"; - public static final String LOAD_ERROR_MESSAGE = "\terror in loading file: will be initialising empty list instead!\n"; - public static final String INVALID_DATE_MESSAGE = "\tThe date you've input is before the current date!\n"; - public static final String WRONG_DATE_FORMAT_TEXT = "\tYou've entered invalid date or time\n"; - public static final String EMPTY_INDEX = "\tPlease enter a valid index within the range of the list! Eg. restore 1\n"; + private static final String WRONG_TASK_TYPE_TEXT = "\tOnly meeting, assignment, or leave tag are accepted\n"; + private static final String EMPTY_DESCRIPTION_TEXT = "\tYou haven't included the description of you task\n"; + private static final String EMPTY_DATE_TEXT = "\tYou haven't included the date of your task\n"; + private static final String EMPTY_USER_TEXT = "\tYou haven't included the user of your task\n"; + private static final String EMPTY_TASK_TYPE_TEXT = "\tYou haven't specified the type of your task: assignment, meeting, or leave\n"; + private static final String WRITE_ERROR_TEXT = "\tError in writing file, cancelling write process...\n"; + private static final String WRONG_INDEX_FORMAT_TEXT = "\tThe index you've enter is in the wrong format\n"; + private static final String WRONG_TIME_FORMAT_TEXT = "\tYou've entered an invalid time format\n"; + private static final String WRONG_SORT_TYPE_TEXT = "\tPlease enter a valid sort type: " + + "priority, alphabetical or deadline\n"; + private static final String LOG_ERROR_TEXT = "\tError writing to a new log file. Please try again.\n"; + private static final String NEGATIVE_AMOUNT_TEXT = "\tThe amount of time cannot be negative.\n"; + private static final String EMPTY_SUB_TASK = "\tYou haven't included your list of sub-tasks\n"; + private static final String DUPLICATE_SUB = "\tDuplicate subtask detected\n"; + private static final String LEAVE_DONE = "\tLeave cannot be set to done\n"; + private static final String INVALID_INPUT_TEXT = "\tYour input String seems to be wrong.\n" + + "\tPlease check your formatting and ensure that the use of special characters are correct!\n"; + private static final String LOAD_ERROR_MESSAGE = "\terror in loading file: will be initialising empty list instead!\n"; + private static final String INVALID_DATE_MESSAGE = "\tThe date you've input is before the current date!\n"; + private static final String WRONG_DATE_FORMAT_TEXT = "\tYou've entered invalid date or time\n"; + private static final String EMPTY_INDEX = "\tPlease enter a valid index within the range of the list! Eg. restore 1\n"; private static final String INVALID_LEAVE_DATE_MESSAGE = "\tPlease check your dates for your leave!\n"; private static final String NO_SUCH_SUBTASK = "\tSubtask does not exist!\n"; + private static final String ASSIGNEE_SET_TO_EVERYONE = "\tThere might have been an error when setting the assignee\n" + + "\tIt could be an error in your entry of the assignee field\n" + + "\tHowever, if you had intended to set the assignee to 'everyone', then ignore this message\n"; private String message; + /** - * Constructor for DukeException Exception + * Constructor for DukeException Exception. * Takes in the exception type thrown and prints out the specific error message * @param type type of exception detected */ - public RoomShareException(ExceptionType type){ - switch(type) { + public RoomShareException(ExceptionType type) { + switch (type) { case emptyUser: message = EMPTY_USER_TEXT; @@ -147,6 +152,10 @@ public RoomShareException(ExceptionType type){ message = NO_SUCH_SUBTASK; break; + case assigneeSetToEveyone: + message = ASSIGNEE_SET_TO_EVERYONE; + break; + default: message = ANOMALY_TEXT; break; @@ -154,11 +163,11 @@ public RoomShareException(ExceptionType type){ } /** - * toString() method returning the message of the Exception + * toString() method returning the message of the Exception. * @return the message of the Exception */ @Override - public String toString(){ + public String toString() { return LINE + message + LINE; } } diff --git a/src/main/java/CustomExceptions/TimeClashException.java b/src/main/java/CustomExceptions/TimeClashException.java index 871bd9018e..08a87ec9f7 100644 --- a/src/main/java/CustomExceptions/TimeClashException.java +++ b/src/main/java/CustomExceptions/TimeClashException.java @@ -7,20 +7,20 @@ public class TimeClashException extends Exception { private String message; /** - * TimeClashException constructor + * TimeClashException constructor. * Adds the appropriate index to the time clash message * @param index index of task with the clash */ public TimeClashException(int index) { - message = TIME_CLASH_TEXT + "Task: " + (index+1) + "\n"; + message = TIME_CLASH_TEXT + "Task: " + (index + 1) + "\n"; } /** - * toString() method returning the message of the Exception + * toString() method returning the message of the Exception. * @return the message of the Exception */ @Override - public String toString(){ + public String toString() { return LINE + message + LINE; } } diff --git a/src/main/java/Enums/ExceptionType.java b/src/main/java/Enums/ExceptionType.java index f4827778eb..2ce7322712 100644 --- a/src/main/java/Enums/ExceptionType.java +++ b/src/main/java/Enums/ExceptionType.java @@ -1,35 +1,31 @@ package Enums; public enum ExceptionType { - wrongTimeFormat, - wrongIndexFormat, - wrongSortFormat, - wrongTaskType, - wrongFormat, - wrongPriority, - wrongDateFormat, - negativeTimeAmount, - - timeClash, - emptyList, - emptyUser, - outOfBounds, - emptySubTask, - - leaveDone, - subTaskError, - duplicateSubtask, - - emptyDescription, - emptyDate, - emptyTaskType, - - logError, - writeError, - loadError, - - invalidInputString, - invalidDateRange, - emptyIndex, - noSubtask, invalidDateError - } +wrongTimeFormat, +wrongIndexFormat, +wrongSortFormat, +wrongTaskType, +wrongFormat, +wrongPriority, +wrongDateFormat, +negativeTimeAmount, +emptyList, +emptyUser, +outOfBounds, +emptySubTask, +leaveDone, +subTaskError, +duplicateSubtask, +emptyDescription, +emptyDate, +emptyTaskType, +logError, +writeError, +loadError, +invalidInputString, +invalidDateRange, +emptyIndex, +noSubtask, +invalidDateError, +assigneeSetToEveyone +} diff --git a/src/main/java/Enums/HelpType.java b/src/main/java/Enums/HelpType.java deleted file mode 100644 index febace59d6..0000000000 --- a/src/main/java/Enums/HelpType.java +++ /dev/null @@ -1,5 +0,0 @@ -package Enums; - -public enum HelpType { - list, bye, find, done , delete, add, recur, snooze, others, priority, reorder, exit -} diff --git a/src/main/java/Enums/TaskType.java b/src/main/java/Enums/TaskType.java index ff1122c311..6149b0cc97 100644 --- a/src/main/java/Enums/TaskType.java +++ b/src/main/java/Enums/TaskType.java @@ -1,6 +1,27 @@ package Enums; public enum TaskType { - list, bye, find, done , delete, time, snooze, others, help, priority, reorder, - restore, add, subtask, update, sort, log, overdue, reschedule, completed, show, removeoverdue +list, +bye, +find, +done, +delete, +time, +snooze, +others, +help, +priority, +reorder, +restore, +add, +subtask, +update, +sort, +log, +overdue, +reschedule, +completed, +show, +removeoverdue, +reopen } diff --git a/src/main/java/Model_Classes/Assignment.java b/src/main/java/Model_Classes/Assignment.java index c98f7b8019..7c7ea99c02 100644 --- a/src/main/java/Model_Classes/Assignment.java +++ b/src/main/java/Model_Classes/Assignment.java @@ -14,41 +14,47 @@ * Stores the description and when the task should be done by. */ public class Assignment extends Task { + private ArrayList subTasks = new ArrayList(); + /** * Constructor for the Assignment object. * Takes in inputs for description and date/time the tasks should be done by. * @param description Description of the task * @param by The time the tasks should be done by. */ - public Assignment (String description, Date by) { + public Assignment(String description, Date by) { super(description, by); } /** - * Takes in arraylist of subtasks and sets it as this assignment's subtasks + * Takes in arraylist of subtasks and sets it as this assignment's subtasks. * @param addList array list containing subtasks */ public void addSubTasks(ArrayList addList) { - for(String output : addList) { + for (String output : addList) { subTasks.add(output); } } /** - * Takes in a String, splits it by "," and sets each new String as a subtask of current Task + * Takes in a String, splits it by "," and sets each new String as a subtask of current Task. * @param subTasks string containing subtasks */ - public void addSubTasks(String subTasks) { this.subTasks = new ArrayList<>(Arrays.asList(subTasks.trim().split(","))); } + public void addSubTasks(String subTasks) { + this.subTasks = new ArrayList<>(Arrays.asList(subTasks.trim().split(","))); + } /** - * Returns the ArrayList containing the Assignment's subtasks - * @return ArrayList subtasks. + * Returns the ArrayList containing the Assignment's subtasks. + * @return ArrayList of subtasks as Strings */ - public ArrayList getSubTasks() { return subTasks; } + public ArrayList getSubTasks() { + return subTasks; + } /** - * Removes completed Subtask + * Removes completed Subtask. * @param index index of completed subtask * @throws RoomShareException when there is no subtask at that index */ diff --git a/src/main/java/Model_Classes/Leave.java b/src/main/java/Model_Classes/Leave.java index d5b9825c60..5cd1a07199 100644 --- a/src/main/java/Model_Classes/Leave.java +++ b/src/main/java/Model_Classes/Leave.java @@ -13,7 +13,7 @@ public class Leave extends Task { private String user; /** - * constructor for the leave class + * constructor for the leave class. * @param description description of the leave * @param user the person who is taking leave * @param from the start date and time of the leave @@ -27,7 +27,7 @@ public Leave(String description, String user, Date from, Date to) { } /** - * gets the start date of the leave + * gets the start date of the leave. * @return the start date and time of the leave */ public Date getStartDate() { @@ -35,7 +35,7 @@ public Date getStartDate() { } /** - * sets the start date of the leave + * sets the start date of the leave. * @param date the start date and time of the leave */ public void setStartDate(Date date) { @@ -43,7 +43,7 @@ public void setStartDate(Date date) { } /** - * gets the end date of the leave + * gets the end date of the leave. * @return end date and time of the leave */ public Date getEndDate() { @@ -51,7 +51,7 @@ public Date getEndDate() { } /** - * sets the end date of the leave + * sets the end date of the leave. * @param date the end date and time of the leave */ public void setEndDate(Date date) { @@ -59,7 +59,7 @@ public void setEndDate(Date date) { } /** - * gets the user who is being assigned to the leave + * gets the user who is being assigned to the leave. * @return user who is assigned the leave */ @Override @@ -68,11 +68,19 @@ public String getAssignee() { } /** - * returns the information of the leave being taken + * returns the information of the leave being taken. * @return String with the information of the leave. */ @Override public String toString() { return "[L] " + super.getDescription() + " (" + user + ")" + " (From: " + from + " To: " + to + ")"; } + + /** + * setter for user. + * @param user name of user for the leave + */ + public void setUser(String user) { + this.user = user; + } } \ No newline at end of file diff --git a/src/main/java/Model_Classes/Meeting.java b/src/main/java/Model_Classes/Meeting.java index 0eaf446a31..c13d431e97 100644 --- a/src/main/java/Model_Classes/Meeting.java +++ b/src/main/java/Model_Classes/Meeting.java @@ -11,7 +11,7 @@ public class Meeting extends Task { private int duration = 0; private TimeUnit timeUnit; /** - * Constructor for Meeting object + * Constructor for Meeting object. * Takes in inputs for description of the meeting and the time the meeting occurs * @param description Description of the meeting * @param at Time the meeting happens @@ -23,7 +23,7 @@ public Meeting(String description, Date at) { } /** - * overload constructor for meeting class + * overload constructor for meeting class. * duration is specified in this constructor * @param description description of the meeting * @param date date and time the meeting starts @@ -37,20 +37,21 @@ public Meeting (String description, Date date, int duration, TimeUnit unit) { } /** - * Returns a string that has the full description of the meeting including the occurrence time + * Returns a string that has the full description of the meeting including the occurrence time. * @return A string indicating the task type, description and the occurrence of the task */ @Override public String toString() { - if (this.isFixedDuration()){ - return "[M]" + super.toString() + " (on: " + super.getDate() + ") (duration: " + duration + " " + timeUnit.toString() + ")"; + if (this.isFixedDuration()) { + return "[M]" + super.toString() + " (on: " + super.getDate() + + ") (duration: " + duration + " " + timeUnit.toString() + ")"; } else { return "[M]" + super.toString() + " (on: " + super.getDate() + ")"; } } /** - * checks if the meeting is fixed duration + * checks if the meeting is fixed duration. * @return true if meeting does not have an undefined time unit */ public boolean isFixedDuration() { @@ -59,7 +60,7 @@ public boolean isFixedDuration() { } /** - * sets the duration of the meeting + * sets the duration of the meeting. * @param duration duration in numbers of the meeting * @param timeUnit time unit of the meeting (minutes, hours, days, months, undefined) */ @@ -69,7 +70,7 @@ public void setDuration(int duration, TimeUnit timeUnit) { } /** - * gets the duration of the meeting + * gets the duration of the meeting. * @return duration of the meeting as a String. */ public String getDuration() { @@ -77,7 +78,7 @@ public String getDuration() { } /** - * gets the time unit of the meeting + * gets the time unit of the meeting. * @return timeunit of the meeting */ public TimeUnit getTimeUnit() { diff --git a/src/main/java/Model_Classes/ProgressBar.java b/src/main/java/Model_Classes/ProgressBar.java index 4a3b867d1f..51c6f729ed 100644 --- a/src/main/java/Model_Classes/ProgressBar.java +++ b/src/main/java/Model_Classes/ProgressBar.java @@ -9,7 +9,7 @@ public class ProgressBar { private float done; /** - * Constructor for Progress Bar + * Constructor for Progress Bar. * @param total Total number of tasks that are in the task list * @param done Total number of completed tasks in the task list */ @@ -19,21 +19,22 @@ public ProgressBar(float total, float done) { } /** - * Displays the number of tasks completed to the total number of task in + * Displays the number of tasks completed to the total number of task in. * a progress bar format. */ public String showBar() { - for (int i=0; i<50; i++) { + for (int i = 0; i < 50; i++) { bar[i] = " "; } - float percentage =0; - if(total >= 1) { + float percentage = 0; + if (total >= 1) { percentage = done / total; - for (int i = 0; i < (int)(percentage*50); i++) { + for (int i = 0; i < (int)(percentage * 50); i++) { bar[i] = "="; } } DecimalFormat df = new DecimalFormat("#.#"); - return Arrays.toString(bar).replace(",", "").trim() + " " + Float.valueOf(df.format(percentage*100)) + "%"; + return Arrays.toString(bar).replace(",", "").trim() + + " " + Float.valueOf(df.format(percentage * 100)) + "%"; } } diff --git a/src/main/java/Model_Classes/Task.java b/src/main/java/Model_Classes/Task.java index 4e0ff349b4..b58edecf02 100644 --- a/src/main/java/Model_Classes/Task.java +++ b/src/main/java/Model_Classes/Task.java @@ -8,7 +8,7 @@ import java.util.Date; /** - * Parent class for all other types of tasks + * Parent class for all other types of tasks. */ public abstract class Task{ private String description; @@ -21,10 +21,11 @@ public abstract class Task{ private boolean isOverdue; /** - * Constructor for the task object. takes in the description of the task + * Constructor for the task object. takes in the description of the task. * @param description Description of the task */ public Task(String description, Date date) { + this.description = description; this.isDone = false; this.isOverdue = false; @@ -35,7 +36,7 @@ public Task(String description, Date date) { } /** - * Returns the description of the task + * Returns the description of the task. * @return description Description of the task */ public String getDescription() { @@ -43,20 +44,22 @@ public String getDescription() { } /** - * Set the description of the task + * Set the description of the task. */ public void setDescription(String description) { this.description = description; } /** - * Returns the time of the Task ( deadline of Assignment / time of meeting ) + * Returns the time of the Task (deadline of Assignment / time of meeting). * @return time task is due or starts */ - public Date getDate() { return date; } + public Date getDate() { + return date; + } /** - * Sets the date and time of the task + * Sets the date and time of the task. * @param date date and time of the task */ public void setDate(Date date) { @@ -64,7 +67,7 @@ public void setDate(Date date) { } /** - * returns whether the task has been done + * returns whether the task has been done. * @return isDone The state of completion of the task. */ public boolean getDone() { @@ -75,7 +78,7 @@ public boolean getDone() { * Sets the task to be done */ public void setDone(boolean done) throws RoomShareException { - if( this instanceof Leave ) { + if (this instanceof Leave ) { throw new RoomShareException(ExceptionType.leaveDone); } isDone = done; @@ -90,7 +93,7 @@ public void setOverdue(boolean overdue) { } /** - * Returns String of the assignee that was specified + * Returns String of the assignee that was specified. * @return name of the user */ public String getAssignee() { @@ -98,7 +101,7 @@ public String getAssignee() { } /** - * Set the assignee of the task + * Set the assignee of the task. * @param assignee name of the assignee */ public void setAssignee(String assignee) { @@ -106,13 +109,15 @@ public void setAssignee(String assignee) { } /** - * Returns the priority of the task + * Returns the priority of the task. * @return priority of the task */ - public Priority getPriority() { return priority; } + public Priority getPriority() { + return priority; + } /** - * Sets the priority of the task + * Sets the priority of the task. * @param p priority of the task */ public void setPriority(Priority p) { @@ -120,7 +125,7 @@ public void setPriority(Priority p) { } /** - * Gets the recurrence schedule of the task + * Gets the recurrence schedule of the task. * @return the recurrence schedule of the task */ public RecurrenceScheduleType getRecurrenceSchedule() { @@ -128,7 +133,7 @@ public RecurrenceScheduleType getRecurrenceSchedule() { } /** - * Sets the recurrence schedule of the task + * Sets the recurrence schedule of the task. * @param recurrenceSchedule the recurrence schedule that the task is set to */ public void setRecurrenceSchedule(RecurrenceScheduleType recurrenceSchedule) { @@ -141,7 +146,7 @@ public void setRecurrenceSchedule(RecurrenceScheduleType recurrenceSchedule) { } /** - * Return whether the task is recurred + * Return whether the task is recurred. * @return hasRecurring: whether the task is recurred */ public boolean hasRecurring() { @@ -149,7 +154,7 @@ public boolean hasRecurring() { } /** - * Snoozes the task by set amount of months + * Snoozes the task by set amount of months. * @param amount number of months to snooze */ public void snoozeMonth(int amount) { @@ -157,28 +162,26 @@ public void snoozeMonth(int amount) { } /** - * Snoozes the task by set amount of days + * Snoozes the task by set amount of days. * @param amount number of days to snooze */ public void snoozeDay(int amount) { this.date.setDate(this.date.getDate() + amount);; } - /** - * Snoozes the task by set amount of hours + * Snoozes the task by set amount of hours. * @param amount number of hours to snooze */ - public void snoozeHour(int amount){ + public void snoozeHour(int amount) { this.date.setHours(this.date.getHours() + amount); } - /** - * Snoozes the task by set amount of hours + * Snoozes the task by set amount of hours. * @param amount number of minutes to snooze */ - public void snoozeMinute(int amount){ + public void snoozeMinute(int amount) { this.date.setMinutes(this.date.getMinutes() + amount); } @@ -187,9 +190,10 @@ public void snoozeMinute(int amount){ * @return the information of the task, consisting of status icon, description and assignee */ public String toString() { - if (hasRecurring) + if (hasRecurring) { return " " + getDescription() + " " + "(" + getAssignee() + ") (every " + getRecurrenceSchedule().toString() + ")"; + } return " " + getDescription() + " " + "(" + getAssignee() + ")"; } } diff --git a/src/main/java/Model_Classes/TaskReminder.java b/src/main/java/Model_Classes/TaskReminder.java index 739591b8c5..51cd59223b 100644 --- a/src/main/java/Model_Classes/TaskReminder.java +++ b/src/main/java/Model_Classes/TaskReminder.java @@ -10,7 +10,7 @@ public class TaskReminder { private String description; /** - * constructor for the TaskReminder class + * constructor for the TaskReminder class. * @param description description of the reminder * @param duration duration of the reminder */ @@ -20,7 +20,7 @@ public TaskReminder(String description, int duration) { } /** - * schedules a timer to play a sound when the time is up + * schedules a timer to play a sound when the time is up. */ public void start() { timer.schedule(new TimerTask() { @@ -28,6 +28,7 @@ public void run() { playSound(); timer.cancel(); } + private void playSound() { System.out.println(description + " is completed!!"); Toolkit.getDefaultToolkit().beep(); diff --git a/src/main/java/Operations/CheckAnomaly.java b/src/main/java/Operations/CheckAnomaly.java index f8ceb6dfe2..62be2b7dd6 100644 --- a/src/main/java/Operations/CheckAnomaly.java +++ b/src/main/java/Operations/CheckAnomaly.java @@ -8,12 +8,12 @@ import java.util.Date; /** - * This class checks if there are clashes in timings for meetings + * This class checks if there are clashes in timings for meetings. */ public class CheckAnomaly { /** - * Checks for tasks with the same description when adding a new task + * Checks for tasks with the same description when adding a new task. * @param task task we are checking * @return current index if duplicate detected and -1 if no duplicate detected */ @@ -21,9 +21,11 @@ public static int checkDuplicate(Task task) { String name = task.getDescription(); String assignee = task.getAssignee(); String date = task.getDate().toString(); - for(int i=0; i temp = OverdueList.getOverdueList(); - for(int i=0; i curr = TaskList.currentList(); - for( int i = 0; i curr = TaskList.currentList(); // Goes down list of Tasks - for( int i = 0; i= meetingTime) { - return true; + duration = timeToMilSeconds(Long.parseLong(((Meeting) task).getDuration()), + ((Meeting) task).getTimeUnit()); } + return currTime < meetingTime + duration && currTime >= meetingTime; } return false; } @@ -144,26 +153,30 @@ private static Boolean checkIntersect(Date time, Task task) { private static Boolean checkOverlap(Task first, Task second) { Date date1 = first.getDate(); Date date2 = second.getDate(); - if( date1.getYear() == date2.getYear() && date1.getMonth() == date2.getMonth() && date1.getDay() == date2.getDay() ) { + if (date1.getYear() == date2.getYear() + && date1.getMonth() == date2.getMonth() + && date1.getDay() == date2.getDay()) { long duration1; long duration2; - if( first instanceof Meeting ) { - duration1 = timeToMilSeconds(Integer.parseInt(((Meeting) first).getDuration()), ((Meeting) first).getTimeUnit()); + if (first instanceof Meeting) { + duration1 = timeToMilSeconds(Integer.parseInt(((Meeting) first).getDuration()), + ((Meeting) first).getTimeUnit()); } else { // task is a leave - duration1 = timeToMilSeconds(Integer.parseInt(((Meeting) first).getDuration()), ((Meeting) first).getTimeUnit()); + duration1 = timeToMilSeconds(Integer.parseInt(((Meeting) first).getDuration()), + ((Meeting) first).getTimeUnit()); } - if( second instanceof Meeting ) { - duration2 = timeToMilSeconds(Integer.parseInt(((Meeting) first).getDuration()), ((Meeting) first).getTimeUnit()); + if (second instanceof Meeting) { + duration2 = timeToMilSeconds(Integer.parseInt(((Meeting) first).getDuration()), + ((Meeting) first).getTimeUnit()); } else { // task is a leave - duration2 = timeToMilSeconds(Integer.parseInt(((Meeting) first).getDuration()), ((Meeting) first).getTimeUnit()); + duration2 = timeToMilSeconds(Integer.parseInt(((Meeting) first).getDuration()), + ((Meeting) first).getTimeUnit()); } long time1 = date1.getTime(); long time2 = date2.getTime(); - if( (time1 < time2 + duration2 && time1 >= time2) || (time2 < time1 + duration1 && time2 >= time1) ) { - return true; - } + return (time1 < time2 + duration2 && time1 >= time2) || (time2 < time1 + duration1 && time2 >= time1); } return false; } @@ -176,14 +189,14 @@ private static Boolean checkOverlap(Task first, Task second) { */ private static long timeToMilSeconds(long duration, TimeUnit unit) { switch (unit) { - case day: - return duration * 60 * 60 * 24 * 1000; - case hours: - return duration * 60 * 60 * 1000; - case minutes: - return duration * 60 * 1000; - default: - return duration; + case day: + return duration * 60 * 60 * 24 * 1000; + case hours: + return duration * 60 * 60 * 1000; + case minutes: + return duration * 60 * 1000; + default: + return duration; } } } diff --git a/src/main/java/Operations/Help.java b/src/main/java/Operations/Help.java index 5cebb6eed4..c8ab02abf0 100644 --- a/src/main/java/Operations/Help.java +++ b/src/main/java/Operations/Help.java @@ -6,13 +6,13 @@ public class Help { private Ui ui = new Ui(); /** - * constructor for help class + * constructor for help class. */ public Help() { } /** - * shows the help tips for the command specified by the keyword + * shows the help tips for the command specified by the keyword. * @param keyword the command the user wants tot seek help on */ public void showHelp(String keyword) { @@ -23,62 +23,62 @@ public void showHelp(String keyword) { taskType = TaskType.others; } switch (taskType) { - case add: - ui.helpAdd(); - break; - case delete: - ui.helpDelete(); - break; - case list: - ui.helperList(); - break; - case done: - ui.helpDone(); - break; - case restore: - ui.helpRestore(); - break; - case find: - ui.helpFind(); - break; - case priority: - ui.helpPriority(); - break; - case snooze: - ui.helpSnooze(); - break; - case reorder: - ui.helpReorder(); - break; - case subtask: - ui.helpSubtask(); - break; - case update: - ui.helpUpdate(); - break; - case sort: - ui.helpSort(); - break; - case log: - ui.helpLog(); - break; - case bye: - ui.helpBye(); - break; - case completed: - ui.helpCompleted(); - break; - case overdue: - ui.helpOverdue(); - break; - case reschedule: - ui.helpReschedule(); - break; + case add: + ui.helpAdd(); + break; + case delete: + ui.helpDelete(); + break; + case list: + ui.helperList(); + break; + case done: + ui.helpDone(); + break; + case restore: + ui.helpRestore(); + break; + case find: + ui.helpFind(); + break; + case priority: + ui.helpPriority(); + break; + case snooze: + ui.helpSnooze(); + break; + case reorder: + ui.helpReorder(); + break; + case subtask: + ui.helpSubtask(); + break; + case update: + ui.helpUpdate(); + break; + case sort: + ui.helpSort(); + break; + case log: + ui.helpLog(); + break; + case bye: + ui.helpBye(); + break; + case completed: + ui.helpCompleted(); + break; + case overdue: + ui.helpOverdue(); + break; + case reschedule: + ui.helpReschedule(); + break; } } /** - * shows all commands that can be used with help + * shows all commands that can be used with help. */ public void helpCommandList() { ui.helpList(); diff --git a/src/main/java/Operations/ListRoutine.java b/src/main/java/Operations/ListRoutine.java index 4df6531d0d..053152c73f 100644 --- a/src/main/java/Operations/ListRoutine.java +++ b/src/main/java/Operations/ListRoutine.java @@ -9,7 +9,7 @@ public class ListRoutine { private Ui ui = new Ui(); /** - * constructor for the ListRoutine + * constructor for the ListRoutine. * @param taskList the task list to be listed using the list routine */ public ListRoutine(TaskList taskList, OverdueList overdueList) { @@ -18,7 +18,7 @@ public ListRoutine(TaskList taskList, OverdueList overdueList) { } /** - * the listing method to be used by ListRoutine + * the listing method to be used by ListRoutine. * lists the tasks and the associated information, while showing the progress bar */ public void list() { diff --git a/src/main/java/Operations/OverdueList.java b/src/main/java/Operations/OverdueList.java index 1d704011b6..111a4e66c0 100644 --- a/src/main/java/Operations/OverdueList.java +++ b/src/main/java/Operations/OverdueList.java @@ -8,7 +8,7 @@ import java.util.ArrayList; public class OverdueList { - private static ArrayList Overdue; + private static ArrayList overdue; /** * A constructor for the overdueList class. @@ -16,7 +16,7 @@ public class OverdueList { * @param Overdue ArrayList of Task object to be operated on. */ public OverdueList(ArrayList Overdue) { - this.Overdue = Overdue; + OverdueList.overdue = Overdue; } /** @@ -25,7 +25,7 @@ public OverdueList(ArrayList Overdue) { * Overdued task list. */ public void add(Task task) { - Overdue.add(task); + overdue.add(task); } /** @@ -36,14 +36,14 @@ public void add(Task task) { * @throws RoomShareException if the index entered is not valid */ public void reschedule(int index, TaskList taskList) throws RoomShareException { - if (index < 0 || index > Overdue.size() - 1) { + if (index < 0 || index > overdue.size() - 1) { System.out.println("This are your tasks in your Overdue list"); list(); throw new RoomShareException(ExceptionType.outOfBounds); } else { - taskList.add(Overdue.get(index)); - Overdue.get(index).setOverdue(false); - Overdue.remove(index); + taskList.add(overdue.get(index)); + overdue.get(index).setOverdue(false); + overdue.remove(index); } } @@ -52,15 +52,15 @@ public void reschedule(int index, TaskList taskList) throws RoomShareException { * @throws RoomShareException when the list is empty */ public void list() throws RoomShareException { - if (Overdue.size() == 0) { + if (overdue.size() == 0) { throw new RoomShareException(ExceptionType.emptyList); } else { int listCount = 1; - for (Task output : Overdue) { + for (Task output : overdue) { System.out.println("\t" + listCount + ". " + output.toString()); - if( output instanceof Assignment && !(((Assignment) output).getSubTasks() == null) ) { + if (output instanceof Assignment && !(((Assignment) output).getSubTasks() == null)) { ArrayList subTasks = ((Assignment) output).getSubTasks(); - for(String subtask : subTasks) { + for (String subtask : subTasks) { System.out.println("\t" + "\t" + "-" + subtask); } } @@ -75,35 +75,45 @@ public void list() throws RoomShareException { * @return the task at the specified index in the task list. * @throws RoomShareException when the index specified is out of bounds. */ - public Task get(int index) throws RoomShareException{ + public Task get(int index) throws RoomShareException { try { - return Overdue.get(index); + return overdue.get(index); } catch (IndexOutOfBoundsException e) { throw new RoomShareException(ExceptionType.outOfBounds); } } + /** + * removes overdue items from the list. + * supports ranged based deletion + * @param index array of indices of tasks to be removed + * @param deletedList list for temporary storage to dump the overdue items into + * @throws RoomShareException when the indices specified are out of bounds + */ public void remove(int[] index, TempDeleteList deletedList) throws RoomShareException { int[] idx = index.clone(); if (idx.length == 1) { - if (idx[0] < 0 || idx[0] >= Overdue.size()) { + if (idx[0] < 0 || idx[0] >= overdue.size()) { throw new RoomShareException(ExceptionType.outOfBounds); } - deletedList.add(Overdue.get(idx[0])); - Overdue.remove(idx[0]); - } - else { - if (idx[0] < 0 || idx[0] >= Overdue.size() || idx[1] < 0 || idx[1] >= Overdue.size()) { + deletedList.add(overdue.get(idx[0])); + overdue.remove(idx[0]); + } else { + if (idx[0] < 0 || idx[0] >= overdue.size() || idx[1] < 0 || idx[1] >= overdue.size()) { throw new RoomShareException(ExceptionType.outOfBounds); } for (int i = idx[0]; idx[1] >= idx[0]; idx[1]--) { - deletedList.add(Overdue.get(i)); - Overdue.remove(i); + deletedList.add(overdue.get(i)); + overdue.remove(i); } } } + /** + * gets the current overdue list. + * @return ArrayList of tasks representing the overdue list + */ public static ArrayList getOverdueList() { - return Overdue; + return overdue; } } diff --git a/src/main/java/Operations/Parser.java b/src/main/java/Operations/Parser.java index 2a5c69ec96..041f1d3590 100644 --- a/src/main/java/Operations/Parser.java +++ b/src/main/java/Operations/Parser.java @@ -15,38 +15,36 @@ import java.util.Scanner; /** - * A class for handling all parsing for Duke. Makes sure that inputs by the user + * A class for handling all parsing for Duke. Makes sure that inputs by the user. * are properly formatted as parameters for other classes. */ public class Parser { private Scanner scanner = new Scanner(System.in); /** - * Constructor for the Parser object + * Constructor for the Parser object. */ public Parser() { } /** - * Returns the command that the user has given RoomShare - * @return command The command given by the user to RoomShare + * Returns the command that the user has given RoomShare. + * @return The command given by the user to RoomShare */ public String getCommand() { - String command = scanner.next().toLowerCase().trim(); - return command; + return scanner.next().toLowerCase().trim(); } /** - * Return the line of command that the user has given Duke - * @return command The line of command given by the user to RoomShare + * Return the line of command that the user has given Duke. + * @return The line of command given by the user to RoomShare */ public String getCommandLine() { - String command = scanner.nextLine().toLowerCase().trim(); - return command; + return scanner.nextLine().toLowerCase().trim(); } /** - * Returns the index number requested by the user for commands like 'snooze, update' + * Returns the index number requested by the user for commands like 'snooze, update'. * @param input the input the user has entered * @return the index the user wishes to perform operations on. * @throws RoomShareException when the format is invalid @@ -54,15 +52,14 @@ public String getCommandLine() { public Integer getIndex(String input) throws RoomShareException { try { String[] arr = input.trim().split(" "); - int index = Integer.parseInt(arr[0]) - 1; - return index; + return Integer.parseInt(arr[0]) - 1; } catch (IllegalArgumentException e) { throw new RoomShareException(ExceptionType.emptyIndex); } } /** - * Return the first/second/... index number requested by the user for command like 'reorder' + * Return the first/second/... index number requested by the user for command like 'reorder'. * @param input the input the user has entered * @param ordinal the first/second/... * @return the index the user wishes to perform operations on. @@ -71,8 +68,7 @@ public Integer getIndex(String input) throws RoomShareException { public Integer getIndex(String input, int ordinal) throws RoomShareException { try { String[] arr = input.trim().split(" "); - int index = Integer.parseInt(arr[ordinal]) - 1 ; - return index; + return Integer.parseInt(arr[ordinal]) - 1; } catch (IllegalArgumentException | IndexOutOfBoundsException e) { throw new RoomShareException(ExceptionType.wrongIndexFormat); } @@ -85,15 +81,14 @@ public Integer getIndex(String input, int ordinal) throws RoomShareException { public Integer getIndexSubtask(String input) throws RoomShareException { try { String[] arr = input.trim().split(" "); - int index = Integer.parseInt(arr[0]) - 1; - return index; + return Integer.parseInt(arr[0]) - 1; } catch (IllegalArgumentException e) { throw new RoomShareException(ExceptionType.wrongIndexFormat); } } /** - * Return the sub-tasks list from the user's input + * Return the sub-tasks list from the user's input. * @param input the input the user has entered * @return the sub-tasks list as a String * @throws RoomShareException when there is no sub-tasks list @@ -108,7 +103,7 @@ public String getSubTasks(String input) throws RoomShareException { } /** - * Return a single index number or a range of index number requested by users for command 'done' and 'delete' + * Return a single index number or a range of index number requested by users for command 'done' and 'delete'. * @return a single index or a range of index */ public int[] getIndexRange(String input) throws RoomShareException { @@ -117,8 +112,9 @@ public int[] getIndexRange(String input) throws RoomShareException { int[] index; if (temp.length == 1) { index = new int[]{Integer.parseInt(temp[0].trim()) - 1}; - } else + } else { index = new int[]{Integer.parseInt(temp[0].trim()) - 1, Integer.parseInt(temp[1].trim()) - 1}; + } return index; } catch (IllegalArgumentException e) { throw new RoomShareException(ExceptionType.wrongIndexFormat); @@ -126,20 +122,20 @@ public int[] getIndexRange(String input) throws RoomShareException { } /** - * Returns a Date object from a raw date that is stored as a String in any format + * Returns a Date object from a raw date that is stored as a String in any format. * @param by Input String containing the date information. * @return A Date object containing the appropriately formatted date. * @throws RoomShareException if the input is uninterpretable. */ public Date formatDate(String by) throws RoomShareException { Date date; - if (this.formatDateCustom_2(by) != null) - date = this.formatDateCustom_2(by); - else if (this.formatDateCustom_3(by) != null) - date = this.formatDateCustom_3(by); - else - date = this.formatDateCustom_1(by); - + if (this.formatDateTomorrowToday(by) != null) { + date = this.formatDateTomorrowToday(by); + } else if (this.formatDateByDay(by) != null) { + date = this.formatDateByDay(by); + } else { + date = this.formatDateDDMMYY(by); + } return date; } @@ -151,7 +147,7 @@ else if (this.formatDateCustom_3(by) != null) * @return A Date object containing the appropriately formatted date. * @throws RoomShareException If by is not in dd/MM/yyyy HH:mm format */ - public Date formatDateCustom_1(String by) throws RoomShareException { + public Date formatDateDDMMYY(String by) throws RoomShareException { try { SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm"); format.setLenient(false); @@ -164,65 +160,58 @@ public Date formatDateCustom_1(String by) throws RoomShareException { } /** - * Returns a Date object from a raw date that is stored as a String with special key words like "tomorrow, today" + * Returns a Date object from a raw date that is stored as a String with special key words like "tomorrow, today". * @param by Input String containing the date information. * @return A Date object containing the appropriately formatted date. */ - public Date formatDateCustom_2(String by) { + public Date formatDateTomorrowToday(String by) { try { Date date = new Date(); String[] temp = by.split(" "); String day = temp[0]; String[] time = temp[1].trim().split(":"); - // validate hours and minute SimpleDateFormat format = new SimpleDateFormat("HH:mm"); format.setLenient(false); format.parse(temp[1].trim()); - // extract hours and minutes int hours = Integer.parseInt(time[0]); int minutes = Integer.parseInt(time[1]); date.setHours(hours); date.setMinutes(minutes); date.setSeconds(0); - if (day.toLowerCase().equals("tomorrow") || day.toLowerCase().equals("tmr")) { date.setDate(date.getDate() + 1); return date; - } - else if (day.toLowerCase().equals("today") || day.toLowerCase().equals("tdy")) { + } else if (day.toLowerCase().equals("today") || day.toLowerCase().equals("tdy")) { return date; + } else { + return null; } - else return null; - } catch (IndexOutOfBoundsException | IllegalArgumentException | ParseException e) { return null; } } /** - * Returns a Date object from a raw date that is stored as a String with special key words like "next monday, this fri" + * Returns a Date object from a raw date that is stored as a String with special key words like "next monday, this fri". * @param by Input String containing the date information. * @return A Date object containing the appropriately formatted date. */ - public Date formatDateCustom_3(String by) { + public Date formatDateByDay(String by) { try { LocalDate date = LocalDate.now(); DayOfWeek currentDayOfWeek = date.getDayOfWeek(); Date outputDate; - String[] temp = by.split(" "); - // validate hours and minute SimpleDateFormat format = new SimpleDateFormat("HH:mm"); format.setLenient(false); format.parse(temp[2].trim()); - // Check if the user enter proper keyword "next" or "this" - if (!temp[0].toLowerCase().equals("next") && !temp[0].toLowerCase().equals("this")) + if (!temp[0].toLowerCase().equals("next") && !temp[0].toLowerCase().equals("this")) { return null; - + } // Check which day of the week the user input String day = temp[1].trim(); DayOfWeek dayOfWeek; @@ -240,25 +229,22 @@ public Date formatDateCustom_3(String by) { dayOfWeek = DayOfWeek.SATURDAY; } else if (day.toLowerCase().equals("sunday") || day.toLowerCase().equals("sun")) { dayOfWeek = DayOfWeek.SUNDAY; - } else + } else { return null; - + } if (temp[0].toLowerCase().equals("this")) { date = date.with(TemporalAdjusters.nextOrSame(dayOfWeek)); - } - else { + } else { if (currentDayOfWeek.getValue() < dayOfWeek.getValue()) { date = date.with(TemporalAdjusters.next(dayOfWeek)); date = date.with(TemporalAdjusters.next(dayOfWeek)); - } - else + } else { date = date.with(TemporalAdjusters.next(dayOfWeek)); + } } - // Convert LocalDate object to Date object for storing compatibility ZoneId defaultZoneId = ZoneId.systemDefault(); outputDate = Date.from(date.atStartOfDay(defaultZoneId).toInstant()); - // Set hours and minute as specified String[] time = temp[2].trim().split(":"); int hours = Integer.parseInt(time[0]); @@ -277,29 +263,27 @@ public Date formatDateCustom_3(String by) { * @return key A string of the keyword to be searched for */ public String getKey() { - String key = scanner.nextLine().trim(); - return key; + return scanner.nextLine().trim(); } /** - * Returns the amount of time the customer request to snooze + * Returns the amount of time the customer request to snooze. * @return the amount of time the customer request to snooze */ - public int getAmount(String input) throws RoomShareException{ + public int getAmount(String input) throws RoomShareException { try { String[] arr = input.trim().split(" "); - int amount = Integer.parseInt(arr[1]); - return amount; + return Integer.parseInt(arr[1]); } catch (IllegalArgumentException | IndexOutOfBoundsException e) { throw new RoomShareException(ExceptionType.wrongTimeFormat); } } /** - * Returns the unit of time the customer request to snooze + * Returns the unit of time the customer request to snooze. * @return the unit of time the customer request to snooze */ - public TimeUnit getTimeUnit(String input) throws RoomShareException{ + public TimeUnit getTimeUnit(String input) throws RoomShareException { try { String[] arr = input.trim().split(" "); return TimeUnit.valueOf(arr[2]); @@ -312,28 +296,31 @@ public TimeUnit getTimeUnit(String input) throws RoomShareException{ /** - * Returns the index of the task and priority the user wants to set it to + * Returns the index of the task and priority the user wants to set it to. * @return the index and priority of the task the user wants to set */ public String[] getPriority() { return scanner.nextLine().trim().split(" ", 2); } + /** + * Gets the input and converts it into a sort type. + * @param input input of the sort type + * @return the input as an enum of sort type + * @throws RoomShareException when sort type specified is not valid + */ public SortType getSort(String input) throws RoomShareException { try { - SortType sortType = SortType.valueOf(input.trim()); - return sortType; + return SortType.valueOf(input.trim()); } catch (IllegalArgumentException e) { throw new RoomShareException(ExceptionType.wrongSortFormat); } - } /** - * Closes the scanner used in Parser class + * Closes the scanner used in Parser class. */ public void close() { scanner.close(); } - } diff --git a/src/main/java/Operations/RecurHandler.java b/src/main/java/Operations/RecurHandler.java index 2a05f649a0..f35bb4b661 100644 --- a/src/main/java/Operations/RecurHandler.java +++ b/src/main/java/Operations/RecurHandler.java @@ -2,7 +2,9 @@ import CustomExceptions.RoomShareException; import Enums.RecurrenceScheduleType; -import Model_Classes.*; +import Model_Classes.Assignment; +import Model_Classes.Meeting; +import Model_Classes.Task; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; @@ -10,22 +12,24 @@ import java.util.Date; /** - * This class deals with operations for Recurring Tasks + * This class deals with operations for Recurring Tasks. * will perform operations such as add, list, find * also checks for recurrence of tasks */ public class RecurHandler { - public static final String DATE_ERROR_SET_AS_NOT_DONE = "Error in parsing date, will be setting the task to not done instead"; + public static final String DATE_ERROR_SET_AS_NOT_DONE = "Error in parsing date, will be setting the task " + + "to not done instead"; private TaskList taskList; private Parser parser = new Parser(); /** - * Constructor for RecurHandler class + * Constructor for RecurHandler class. * @param recurringList The TaskList to be operated on using RecurHandler */ public RecurHandler(TaskList recurringList) { this.taskList = recurringList; } + /** * Checks for recurrences based on the date. * if there is a recurrence, replaces the old recurring task with a new one @@ -48,14 +52,14 @@ public boolean checkRecurrence() throws RoomShareException { // check if recurrence date has passed if (dateHasPassedOthers(currentTime, check, isEdited)) { if (check instanceof Assignment) { - Assignment recurringAssignment= new Assignment(description, getNewDate(check)); + Assignment recurringAssignment = new Assignment(description, getNewDate(check)); recurringAssignment.setRecurrenceSchedule(type); recurringAssignment.setPriority(check.getPriority()); recurringAssignment.setAssignee(check.getAssignee()); taskList.replace(index, recurringAssignment); isEdited = true; } else { - Meeting recurringMeeting= new Meeting(description, getNewDate(check)); + Meeting recurringMeeting = new Meeting(description, getNewDate(check)); recurringMeeting.setRecurrenceSchedule(type); recurringMeeting.setPriority(check.getPriority()); recurringMeeting.setAssignee(check.getAssignee()); @@ -82,7 +86,7 @@ private Date getNewDate(Task check) { Calendar calendar = Calendar.getInstance(); String date = new Storage().convertForStorage(check); date = date.substring(0, 15); - Date storedDate = parser.formatDateCustom_1(date); + Date storedDate = parser.formatDateDDMMYY(date); calendar.setTime(storedDate); if (check.getRecurrenceSchedule().equals(RecurrenceScheduleType.day)) { calendar.add(Calendar.DAY_OF_MONTH, 1); @@ -110,7 +114,7 @@ private Date getNewDate(Task check) { private boolean dateHasPassedOthers(String currentTime, Task check, boolean isEdited) throws RoomShareException { boolean isPassed = false; try { - Date current = parser.formatDateCustom_1(currentTime); + Date current = parser.formatDateDDMMYY(currentTime); Date newDate = getNewDate(check); if (newDate.compareTo(current) < 0) { // date has passed diff --git a/src/main/java/Operations/Storage.java b/src/main/java/Operations/Storage.java index 689863948b..a905e8eb30 100644 --- a/src/main/java/Operations/Storage.java +++ b/src/main/java/Operations/Storage.java @@ -2,9 +2,13 @@ import CustomExceptions.RoomShareException; import Enums.*; -import Model_Classes.*; +import Model_Classes.Assignment; +import Model_Classes.Leave; +import Model_Classes.Meeting; +import Model_Classes.Task; import java.io.*; +import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -12,13 +16,12 @@ import java.util.Date; /** - * Performs storage operations such as writing and reading from a .txt file + * Performs storage operations such as writing and reading from a .txt file. */ public class Storage { - private Parser parser; /** - * Constructor for the Storage class + * Constructor for the Storage class. */ public Storage() { } @@ -41,7 +44,7 @@ public ArrayList loadFile(String fileName) throws RoomShareException { while ((line = bufferedReader.readLine()) != null) { tempList.add(line); } - parser = new Parser(); + Parser parser = new Parser(); for (String list : tempList) { String[] temp = list.split("#"); @@ -68,8 +71,7 @@ public ArrayList loadFile(String fileName) throws RoomShareException { priority = Priority.low; } - String scanDescription = temp[3].trim(); - String description = scanDescription; + String description = temp[3].trim(); Date from = new Date(); Date to = new Date(); @@ -78,20 +80,20 @@ public ArrayList loadFile(String fileName) throws RoomShareException { String[] dateArray = temp[4].trim().split("-"); String scanFromDate = dateArray[0].trim(); try { - from = parser.formatDateCustom_1(scanFromDate); + from = parser.formatDateDDMMYY(scanFromDate); } catch (RoomShareException e) { System.out.println("error in loading file: date format error"); } String scanToDate = dateArray[1].trim(); try { - to = parser.formatDateCustom_1(scanToDate); + to = parser.formatDateDDMMYY(scanToDate); } catch (RoomShareException e) { System.out.println("error in loading file: date format error"); } } else { String scanDate = temp[4].trim(); try { - date = parser.formatDateCustom_1(scanDate); + date = parser.formatDateDDMMYY(scanDate); } catch (RoomShareException e) { System.out.println("error in loading file: date format error"); } @@ -105,8 +107,7 @@ public ArrayList loadFile(String fileName) throws RoomShareException { throw new RoomShareException(ExceptionType.loadError); } - String scanUser = temp[6].trim(); - String user = scanUser; + String user = temp[6].trim(); String scanIsFixedDuration = temp[7].trim(); boolean isFixedDuration = scanIsFixedDuration.equals("F"); @@ -138,7 +139,9 @@ public ArrayList loadFile(String fileName) throws RoomShareException { assignment.setAssignee(user); assignment.setRecurrenceSchedule(recurrence); assignment.setDone(done); - if (!scanSubTask.equals("")) assignment.addSubTasks(scanSubTask); + if (!scanSubTask.equals("")) { + assignment.addSubTasks(scanSubTask); + } taskArrayList.add(assignment); } else if (type.equals(SaveType.L)) { //Leave type @@ -194,16 +197,11 @@ public void writeFile(ArrayList list, String fileName) throws RoomShareExc String recurrence = s.getRecurrenceSchedule().toString(); String user = s.getAssignee(); if (s instanceof Assignment) { - out = type + "#" + - isDone + "#" + - priority + "#" + - description + "#" + - date + "#" + - recurrence + "#" + - user + "#" + - "N" + "#" + - "0" + "#" + - "unDefined" + "#"; + out = type + "#" + isDone + "#" + + priority + "#" + description + "#" + + date + "#" + recurrence + "#" + + user + "#" + "N" + "#" + + "0" + "#" + "unDefined" + "#"; // Saves sub-tasks if (!(((Assignment) s).getSubTasks() == null)) { ArrayList subTasks = ((Assignment) s).getSubTasks(); @@ -214,44 +212,26 @@ public void writeFile(ArrayList list, String fileName) throws RoomShareExc out += "#"; } else if (s instanceof Leave) { String leaveDate = convertForStorageLeave(s); - out = type + "#" + - isDone + "#" + - priority + "#" + - description + "#" + - leaveDate + "#" + - recurrence + "#" + - user + "#" + - "N" + "#" + - "0" + "#" + - "unDefined" + "#" - + "#"; + out = type + "#" + isDone + "#" + + priority + "#" + description + "#" + + leaveDate + "#" + recurrence + "#" + + user + "#" + "N" + "#" + + "0" + "#" + "unDefined" + "#" + "#"; } else if (s instanceof Meeting) { if (((Meeting) s).isFixedDuration()) { String duration = ((Meeting) s).getDuration(); String unit = ((Meeting) s).getTimeUnit().toString(); - out = type + "#" + - isDone + "#" + - priority + "#" + - description + "#" + - date + "#" + - recurrence + "#" + - user + "#" + - "F" + "#" + - duration + "#" + - unit + "#" - + "#"; + out = type + "#" + isDone + "#" + + priority + "#" + description + "#" + + date + "#" + recurrence + "#" + + user + "#" + "F" + "#" + + duration + "#" + unit + "#" + "#"; } else { - out = type + "#" + - isDone + "#" + - priority + "#" + - description + "#" + - date + "#" + - recurrence + "#" + - user + "#" + - "N" + "#" + - "0" + "#" + - "unDefined" + "#" - + "#"; + out = type + "#" + isDone + "#" + + priority + "#" + description + "#" + + date + "#" + recurrence + "#" + + user + "#" + "N" + "#" + + "0" + "#" + "unDefined" + "#" + "#"; } } writer.write(out); @@ -264,10 +244,9 @@ public void writeFile(ArrayList list, String fileName) throws RoomShareExc } /** - * Create a new text file and write all information of the current task list to it + * Create a new text file and write all information of the current task list to it. * @param list the current task list - * @throws IOException when there's error creating or writing to file - * @throws FileNotFoundException when there's error creating or writing to file + * @throws RoomShareException when there is an error in writing the log file */ public String writeLogFile(ArrayList list) throws RoomShareException { String fileName = "log " + new Date().toString() + ".txt"; @@ -279,7 +258,7 @@ public String writeLogFile(ArrayList list) throws RoomShareException { File folder = new File(folderName); if (!folder.exists()) folder.mkdir(); file.createNewFile(); - PrintWriter writer = new PrintWriter(filePath, "UTF-8"); + PrintWriter writer = new PrintWriter(filePath, StandardCharsets.UTF_8); for (Task t : list) { writer.println(t.toString()); } @@ -348,15 +327,15 @@ public String convertForStorageLeave(Task task) throws RoomShareException { String fromDay = tempString[3]; String toDay = tempString[10]; - time = fromDay + "/" + fromMth + "/" + fromYear + " " + fromTimeArray[0] + ":" + fromTimeArray[1] + "-" + - toDay + "/" + toMth + "/" + toYear + " " + toTimeArray[0] + ":" + toTimeArray[1]; - + time = fromDay + "/" + fromMth + "/" + fromYear + + " " + fromTimeArray[0] + ":" + fromTimeArray[1] + "-" + + toDay + "/" + toMth + "/" + toYear + + " " + toTimeArray[0] + ":" + toTimeArray[1]; return time; } catch (ParseException e) { throw new RoomShareException(ExceptionType.wrongFormat); } } - } diff --git a/src/main/java/Operations/TaskCreator.java b/src/main/java/Operations/TaskCreator.java index 55a852a013..fb36ed6406 100644 --- a/src/main/java/Operations/TaskCreator.java +++ b/src/main/java/Operations/TaskCreator.java @@ -8,33 +8,31 @@ import Enums.RecurrenceScheduleType; import Enums.TimeUnit; import Model_Classes.*; - import javafx.util.Pair; + import java.util.ArrayList; -import java.util.Timer; import java.util.Date; public class TaskCreator { - public static final String UPDATED_DESCRIPTION_ERROR = "There is a formatting error in your updated description"; - public static final String DURATION_FORMAT_ERROR = "There's a problem with the duration you've specified, default to no duration"; - public static final String RECURRENCE_FORMAT_ERROR = "There seems to some mistake in your recurrence entry, will be setting recurrence as none"; - public static final String DATE_FORMAT_ERROR = "Wrong date format, date is set default to current date"; - public static final String STARTING_DATE_FORMAT_ERROR = "Wrong date format, starting date is set default to current date"; - public static final String ENDING_DATE_FORMAT_ERROR = "Wrong date format, ending date is set default to current date"; - public static final String UPDATED_DATE_ERROR = "Please check the updated date of your task"; + private static final String UPDATED_DESCRIPTION_ERROR = "There is a formatting error in your updated description"; + private static final String DURATION_FORMAT_ERROR = "There's a problem with the duration you've specified, default to no duration"; + private static final String RECURRENCE_FORMAT_ERROR = "There seems to some mistake in your recurrence entry, " + +"will be setting recurrence as none"; + private static final String STARTING_DATE_FORMAT_ERROR = "Wrong date format, starting date is set default to current date"; + private static final String ENDING_DATE_FORMAT_ERROR = "Wrong date format, ending date is set default to current date"; + public static final String PRIORITY_WILL_BE_SET_AS_LOW = "There seems to some mistake in your priority entry," + + " will be setting priority as low"; private Parser parser; - Timer timer; /** - * Constructor for a TaskCreator + * Constructor for a TaskCreator. */ public TaskCreator() { parser = new Parser(); - timer = new Timer(); } /** - * Extract the task type from the user's input + * Extract the task type from the user's input. * @param input user's input * @return the task type * @throws RoomShareException when the task type is invalid @@ -42,16 +40,16 @@ public TaskCreator() { public String extractType(String input) throws RoomShareException { String[] typeArray = input.split("#"); String type; - if (typeArray.length != 1) + if (typeArray.length != 1) { type = typeArray[1].toLowerCase(); - else + } else { throw new RoomShareException(ExceptionType.emptyTaskType); - + } return type; } /** - * Extract the description of a task from user's input + * Extract the description of a task from user's input. * @param input user's input * @return the description of the task * @throws RoomShareException when there's no description detected @@ -62,8 +60,9 @@ public String extractDescription(String input) throws RoomShareException { if (descriptionArray.length != 1) { String[] descriptionArray2 = descriptionArray[1].trim().split("\\)"); description = descriptionArray2[0].trim(); - } else + } else { throw new RoomShareException(ExceptionType.emptyDescription); + } if (hasSpecialCharacters(description)) { throw new RoomShareException(ExceptionType.invalidInputString); } @@ -71,11 +70,22 @@ public String extractDescription(String input) throws RoomShareException { } /** - * Extract the priority of a task from user's input + * Extract the priority of a task from user's input. * @param input user's input * @return the priority of the task */ - public Priority extractPriority(String input) { + public Priority extractPriority(String input) throws RoomShareException { + // check for errors in the raw input for misleading characters + int count = 0; + char[] inputAsChar = input.toCharArray(); + for (char c: inputAsChar) { + if (c == '*') { + count++; + } + } + if (count == 1) { + throw new RoomShareException(ExceptionType.invalidInputString); + } String[] priorityArray = input.split("\\*"); Priority priority; if (priorityArray.length != 1) { @@ -83,18 +93,17 @@ public Priority extractPriority(String input) { try { priority = Priority.valueOf(inputPriority); } catch (IllegalArgumentException e) { - System.out.println("There seems to some mistake in your priority entry, will be setting priority as low"); + System.out.println(PRIORITY_WILL_BE_SET_AS_LOW); priority = Priority.low; } } else { priority = Priority.low; } - return priority; } /** - * Extract the date and time of a task from user's input + * Extract the date and time of a task from user's input. * @param input user's input * @return the date and time of the task * @throws RoomShareException when there is no date and time detected or the format of date and time is invalid @@ -108,15 +117,14 @@ public ArrayList extractDate(String input) throws RoomShareException { count++; } } - String[] dateArray = input.trim().split("&"); ArrayList dates = new ArrayList<>(); Date currentDate = new Date(); if (count > 0) { if (count <= 2) { - String dateInput = dateArray[1].trim(); - Date date; try { + String dateInput = dateArray[1].trim(); + Date date; date = parser.formatDate(dateInput); if (date.before(currentDate)) { // the input date is before the current date @@ -124,7 +132,7 @@ public ArrayList extractDate(String input) throws RoomShareException { } dates.add(date); } catch (ArrayIndexOutOfBoundsException a) { - throw new RoomShareException(ExceptionType.invalidDateError); + throw new RoomShareException(ExceptionType.emptyDate); } } else { String fromInput = dateArray[1].trim(); @@ -155,18 +163,29 @@ public ArrayList extractDate(String input) throws RoomShareException { throw new RoomShareException(ExceptionType.invalidDateRange); } } - } else + } else { throw new RoomShareException(ExceptionType.emptyDate); - + } return dates; } /** - * Extract the assignee of a task from user's input + * Extract the assignee of a task from user's input. * @param input user's input * @return the name of the assignee */ - public String extractAssignee(String input) throws RoomShareException{ + public String extractAssignee(String input) throws RoomShareException { + // check for errors in the raw input for misleading characters + int count = 0; + char[] inputAsChar = input.toCharArray(); + for (char c: inputAsChar) { + if (c == '@') { + count++; + } + } + if (count == 1) { + throw new RoomShareException(ExceptionType.invalidInputString); + } String[] assigneeArray = input.split("@"); String assignee; if (assigneeArray.length != 1) { @@ -182,11 +201,22 @@ public String extractAssignee(String input) throws RoomShareException{ } /** - * Extract the recurrence schedule of task from user's input + * Extract the recurrence schedule of task from user's input. * @param input user's input * @return the recurrence schedule of the task */ - public RecurrenceScheduleType extractRecurrence(String input) { + public RecurrenceScheduleType extractRecurrence(String input) throws RoomShareException { + // check for errors in the raw input for misleading characters + int count = 0; + char[] inputAsChar = input.toCharArray(); + for (char c: inputAsChar) { + if (c == '%') { + count++; + } + } + if (count == 1) { + throw new RoomShareException(ExceptionType.invalidInputString); + } String[] recurrenceArray = input.split("%"); RecurrenceScheduleType recurrence; if (recurrenceArray.length != 1) { @@ -205,11 +235,22 @@ public RecurrenceScheduleType extractRecurrence(String input) { } /** - * Extract the duration of a task from user's input + * Extract the duration of a task from user's input. * @param input user's input - * @return the amount of time and unit of the duration as a Pair + * @return the amount of time and unit of the duration as a Pair of Integer and TimeUnit */ public Pair extractDuration(String input) throws RoomShareException { + // check for errors in the raw input for misleading characters + int count = 0; + char[] inputAsChar = input.toCharArray(); + for (char c: inputAsChar) { + if (c == '^') { + count++; + } + } + if (count == 1) { + throw new RoomShareException(ExceptionType.invalidInputString); + } String[] durationArray = input.split("\\^"); int duration; TimeUnit unit; @@ -228,12 +269,18 @@ public Pair extractDuration(String input) throws RoomShareExc unit = TimeUnit.unDefined; } - if (duration < 0) + if (duration < 0) { throw new RoomShareException(ExceptionType.negativeTimeAmount); + } return new Pair<>(duration,unit); } - public boolean hasSpecialCharacters(String input) { + /** + * Checks if input string has special flags used in the input format. + * @param input input to be checked + * @return a boolean value denoting if the input contains such flags + */ + private boolean hasSpecialCharacters(String input) { boolean isInvalid = false; if (input.contains("#")) { isInvalid = true; @@ -256,24 +303,21 @@ public boolean hasSpecialCharacters(String input) { } /** - * Extract the reminder flag of a task from user's input + * Extract the reminder flag of a task from user's input. * @param input user's input * @return the reminder flag of the task */ public boolean extractReminder(String input) { String[] reminderArray = input.split("!"); if (reminderArray.length != 1) { - if(reminderArray[1].contains("R")) - return true; - else - return false; + return reminderArray[1].contains("R"); } else { return false; } } /** - * Create a new task based on the description the user key in + * Create a new task based on the description the user key in. * @param input the description of the task * @return a new Task object created based on the description * @throws RoomShareException when there are some formatting errors @@ -325,7 +369,7 @@ public Task create(String input) throws RoomShareException, DuplicateException, assignment.setPriority(priority); assignment.setAssignee(assignee); assignment.setRecurrenceSchedule(recurrence); - if(remind) { + if (remind) { TaskReminder taskReminder = new TaskReminder(description, duration); taskReminder.start(); } @@ -340,8 +384,9 @@ public Task create(String input) throws RoomShareException, DuplicateException, String[] leaveUserArray = input.split("@"); if (leaveUserArray.length != 1) { user = leaveUserArray[1].trim(); - } else + } else { throw new RoomShareException(ExceptionType.emptyUser); + } Leave leave = new Leave(description, user, from, to); leave.setPriority(priority); leave.setRecurrenceSchedule(recurrence); @@ -434,15 +479,18 @@ public Task create(String input) throws RoomShareException, DuplicateException, } /** - * Update a task from the task list according to the user's input + * Update a task from the task list according to the user's input. * @param input user's input * @param oldTask the task to be updated */ public void updateTask(String input, Task oldTask) throws RoomShareException { + boolean isNotUpdated = true; + boolean isSetToEveryone = false; try { if (input.contains("(") && input.contains(")")) { String description = this.extractDescription(input); oldTask.setDescription(description); + isNotUpdated = false; } } catch (RoomShareException e) { System.out.println(UPDATED_DESCRIPTION_ERROR); @@ -457,57 +505,71 @@ public void updateTask(String input, Task oldTask) throws RoomShareException { oldLeave.setDate(start); oldLeave.setStartDate(start); oldLeave.setEndDate(end); + isNotUpdated = false; } else { Date date = dates.get(0); if (oldTask instanceof Leave) { Leave oldLeave = (Leave)oldTask; oldLeave.setEndDate(date); + isNotUpdated = false; } else { oldTask.setDate(date); + isNotUpdated = false; } } } - else if (input.contains("*")) { + if (input.contains("*")) { Priority priority = this.extractPriority(input); oldTask.setPriority(priority); + isNotUpdated = false; } - else if (input.contains("@")) { + if (input.contains("@")) { String assignee = null; try { assignee = this.extractAssignee(input); } catch (RoomShareException e) { assignee = "everyone"; } + if (assignee.equals("everyone")) { + isSetToEveryone = true; + } oldTask.setAssignee(assignee); + if (oldTask instanceof Leave) { + Leave oldLeave = (Leave) oldTask; + oldLeave.setUser(assignee); + } + isNotUpdated = false; } - else if (input.contains("^") && oldTask instanceof Meeting) { + if (input.contains("^") && oldTask instanceof Meeting) { Pair durationAndUnit = this.extractDuration(input); int duration = durationAndUnit.getKey(); TimeUnit unit = durationAndUnit.getValue(); Meeting oldMeeting = (Meeting) oldTask; oldMeeting.setDuration(duration,unit); + isNotUpdated = false; } - else if (input.contains("%")) { + if (input.contains("%")) { RecurrenceScheduleType recurrence = this.extractRecurrence(input); oldTask.setRecurrenceSchedule(recurrence); + isNotUpdated = false; } - else if(input.contains("uncheck") && !(oldTask instanceof Leave)) { - boolean checked = oldTask.getDone(); - oldTask.setDone(!checked); + // check if any field was updated at all + if (isNotUpdated) { + throw new RoomShareException(ExceptionType.invalidInputString); } - else { - throw new RoomShareException(ExceptionType.invalidInputString); + if (isSetToEveryone) { + throw new RoomShareException(ExceptionType.assigneeSetToEveyone); } } /** - * Updates the date of the overdue task + * Updates the date of the overdue task. * * @param input user's input of the date * @param overdueTask the task which date needs to be updated diff --git a/src/main/java/Operations/TaskList.java b/src/main/java/Operations/TaskList.java index 07d5ba4d2a..f6c33e2776 100644 --- a/src/main/java/Operations/TaskList.java +++ b/src/main/java/Operations/TaskList.java @@ -15,9 +15,11 @@ import java.util.Date; /** - * A class to perform operations on the task list in Duke + * A class to perform operations on the task list in Duke. */ public class TaskList { + public static final String COMPLETED_TASKS = "Completed Tasks:"; + public static final String YOUR_SEARCH_RETURNED_NO_RESULTS_TRY_SEARCHING_WITH_ANOTHER_KEYWORD = " Your search returned no results.... Try searching with another keyword!"; private static ArrayList tasks; private static SortType sortType = SortType.priority; @@ -31,7 +33,7 @@ public TaskList(ArrayList tasks) { } /** - * Adds a new task into the task list + * Adds a new task into the task list. * @param newTask Task object to be added into the list of tasks */ public void add(Task newTask) { @@ -76,8 +78,8 @@ public void list(OverdueList overdueList) throws RoomShareException { sortTasks(); if (tasks.size() != 0) { int listCount = 1; - for(int i=0; i subTasks = ((Assignment) output).getSubTasks(); for (String subtask : subTasks) { System.out.println("\t" + "\t" + "- " + subtask); @@ -123,18 +125,18 @@ public void list(OverdueList overdueList) throws RoomShareException { } /** - * Lists out completed tasks in the list - * @throws RoomShareException + * Lists out completed tasks in the list. + * @throws RoomShareException when there are no completed tasks */ public void showCompleted() throws RoomShareException { sortTasks(); - System.out.println("Completed Tasks:"); - if( tasks.size() != 0 ){ + System.out.println(COMPLETED_TASKS); + if (tasks.size() != 0){ int listCount = 1; for (Task output : tasks) { - if( output.getDone() ) { + if (output.getDone()) { System.out.println("\t" + listCount + ". " + output.toString()); - if( output instanceof Assignment && !(((Assignment) output).getSubTasks() == null) ) { + if (output instanceof Assignment && (((Assignment) output).getSubTasks() != null)) { ArrayList subTasks = ((Assignment) output).getSubTasks(); for (String subtask : subTasks) { System.out.println("\t" + "\t" + "- " + subtask); @@ -160,8 +162,7 @@ public void done(int[] index) throws RoomShareException { throw new RoomShareException(ExceptionType.outOfBounds); } tasks.get(index[0]).setDone(true); - } - else { + } else { if (index[0] < 0 || index[0] >= tasks.size() || index[1] < 0 || index[1] >= tasks.size()) { throw new RoomShareException(ExceptionType.outOfBounds); } @@ -198,7 +199,7 @@ public void doneSubTask(String input) throws RoomShareException { * Will prompt that the search has no results if keyword does not exist in the list. * @param key Keyword of the search. */ - public void find (String key) { + public void find(String key) { int queryCount = 1; for (Task query : tasks) { if (query.toString().toLowerCase().contains(key.trim())) { @@ -207,12 +208,12 @@ public void find (String key) { } } if (queryCount == 1) { - System.out.println(" Your search returned no results.... Try searching with another keyword!"); + System.out.println(YOUR_SEARCH_RETURNED_NO_RESULTS_TRY_SEARCHING_WITH_ANOTHER_KEYWORD); } } /** - * Returns the entire ArrayList of tasks + * Returns the entire ArrayList of tasks. * @return tasks The ArrayList of Task objects that is being operated on. */ public static ArrayList currentList() { @@ -220,7 +221,7 @@ public static ArrayList currentList() { } /** - * replaces the task at the specified index with a new task + * replaces the task at the specified index with a new task. * @param index index of the task to be replaced * @param replacement the replacement task */ @@ -229,7 +230,7 @@ public void replace(int index, Task replacement) { } /** - * Sets priority of task at an index to a new priority + * Sets priority of task at an index to a new priority. * @param info the information of the task index and the priority it should be set to * @throws RoomShareException when the priority specified is wrong or index is out of bounds */ @@ -247,12 +248,12 @@ public void setPriority(String[] info) throws RoomShareException { } /** - * Returns priority of the task in the form of an integer + * Returns priority of the task in the form of an integer. * high = 0, medium = 1, low = 2 * @param t task in which we are checking the value of * @return integer value of the task's priority */ - public static int getValue(Task t) { + private static int getValue(Task t) { if (t.getPriority().equals(Priority.high)) { return 0; } else if (t.getPriority().equals(Priority.medium)) { @@ -263,7 +264,7 @@ public static int getValue(Task t) { } /** - * Changes taskList sort mode + * Changes taskList sort mode. * @param sortType new sort mode */ public static void changeSort(SortType sortType) { @@ -272,7 +273,7 @@ public static void changeSort(SortType sortType) { } /** - * Sorts the list based on current sort mode + * Sorts the list based on current sort mode. * @throws IllegalArgumentException when the sort type is not of priority, alphabetical or by deadline */ public static void sortTasks() { @@ -295,13 +296,13 @@ public static void sortTasks() { } /** - * Compare tasks based on priority + * Compare tasks based on priority. */ - public static void comparePriority() { + private static void comparePriority() { Collections.sort(tasks, (task1, task2) -> { - if( task1.getDone() && !task2.getDone() ) { + if (task1.getDone() && !task2.getDone()) { return 1; - } else if( task2.getDone() && !task1.getDone() ) { + } else if (task2.getDone() && !task1.getDone()) { return -1; } else { return getValue(task1) - getValue(task2); @@ -310,13 +311,13 @@ public static void comparePriority() { } /** - * Compare tasks based on Alphabetical order + * Compare tasks based on Alphabetical order. */ - public static void compareAlphabetical() { + private static void compareAlphabetical() { Collections.sort(tasks, (task1, task2) -> { - if( task1.getDone() && !task2.getDone() ) { + if (task1.getDone() && !task2.getDone()) { return 1; - } else if( task2.getDone() && !task1.getDone() ) { + } else if (task2.getDone() && !task1.getDone()) { return -1; } else { String name1 = task1.getDescription(); @@ -327,13 +328,13 @@ public static void compareAlphabetical() { } /** - * Compare tasks based on Deadline + * Compare tasks based on Deadline. */ - public static void compareDeadline() { + private static void compareDeadline() { Collections.sort(tasks, (task1, task2) -> { - if( task1.getDone() && !task2.getDone() ) { + if (task1.getDone() && !task2.getDone()) { return 1; - } else if( task2.getDone() && !task1.getDone() ) { + } else if (task2.getDone() && !task1.getDone()) { return -1; } else { Date date1 = task1.getDate(); @@ -344,22 +345,22 @@ public static void compareDeadline() { } /** - * Compare tasks based on Type + * Compare tasks based on Type. */ - public static void compareType() { + private static void compareType() { Collections.sort(tasks, (task1, task2) -> { - if( task1 instanceof Meeting && !(task2 instanceof Meeting) ) { + if (task1 instanceof Meeting && !(task2 instanceof Meeting)) { return -1; - } else if( task1 instanceof Assignment ) { - if( task2 instanceof Meeting ) { + } else if (task1 instanceof Assignment) { + if (task2 instanceof Meeting) { return 1; - } else if( task2 instanceof Leave ) { + } else if (task2 instanceof Leave) { return -1; } else { return 0; } } else { - if( task2 instanceof Meeting || task2 instanceof Assignment ) { + if (task2 instanceof Meeting || task2 instanceof Assignment) { return 1; } else { return 0; @@ -369,7 +370,7 @@ public static void compareType() { } /** - * Reorder the positions of two tasks inside the task list + * Reorder the positions of two tasks inside the task list. * @param first the first task * @param second the second task */ @@ -382,7 +383,7 @@ public void reorder(int first, int second) throws RoomShareException { } /** - * Snooze a specific task indicated by user + * Snooze a specific task indicated by user. * @param index the index of the task to be snoozed * @param amount the amount of time to snooze * @param timeUnit unit for snooze time: month, day, hour, minute @@ -403,21 +404,23 @@ public void snooze (int index, int amount, TimeUnit timeUnit) throws RoomShareEx case minutes: tasks.get(index).snoozeMinute(amount); break; + default: + tasks.get(index).snoozeMinute(0); + break; } - } - catch (IndexOutOfBoundsException e) { + } catch (IndexOutOfBoundsException e) { throw new RoomShareException(ExceptionType.outOfBounds); } } /** - * Get the number of tasks inside the task list + * Get the number of tasks inside the task list. * @return the number of tasks inside the task list */ - public int getSize() { - int count =0; + int getSize() { + int count = 0; for(Task t : tasks) { - if(!t.getOverdue() && !(t instanceof Leave)) { + if (!t.getOverdue() && !(t instanceof Leave)) { count += 1; } } @@ -425,12 +428,12 @@ public int getSize() { } /** - * Get the number of completed tasks inside the task list + * Get the number of completed tasks inside the task list. * @return the number of completed tasks inside the task list */ - public int getDoneSize(){ + int getDoneSize() { int count = 0; - for (Task t: tasks){ + for (Task t: tasks) { if (t.getDone() && !t.getOverdue() && !(t instanceof Leave)) { count++; } @@ -439,12 +442,12 @@ public int getDoneSize(){ } /** - * Retrieve a task from the list + * Retrieve a task from the list. * @param index the index of the task * @return the task at the specified index of the task list * @throws RoomShareException when the index specified is out of bounds */ - public static Task get(int index) throws RoomShareException{ + public static Task get(int index) throws RoomShareException { try { return tasks.get(index); } catch (IndexOutOfBoundsException e) { @@ -453,18 +456,20 @@ public static Task get(int index) throws RoomShareException{ } /** - * Returns current sort type of list + * Returns current sort type of list. * @return current sort type of list */ - public static SortType getSortType() { return sortType; } + static SortType getSortType() { + return sortType; + } /** - * lists out all the tasks associated with a certain assignee + * lists out all the tasks associated with a certain assignee. * will include tasks that are tagged "everyone", since everyone includes the assignee * @param user assignee to the tasks * @throws RoomShareException when the list is empty */ - public int[] listTagged(String user) throws RoomShareException{ + public int[] listTagged(String user) throws RoomShareException { int listCount = 1; int belongCount = 0; int doneCount = 0; @@ -476,16 +481,16 @@ public int[] listTagged(String user) throws RoomShareException{ } if (!output.getDone()) { Priority priority = output.getPriority(); - String priorityLVL; + String priorityLvl; if (priority.equals(Priority.low)) { - priorityLVL = " *"; + priorityLvl = " *"; } else if (priority.equals(Priority.medium)) { - priorityLVL = " **"; + priorityLvl = " **"; } else { - priorityLVL = " ***"; + priorityLvl = " ***"; } - System.out.println("\t" + listCount + ". " + output.toString() + priorityLVL); - if (output instanceof Assignment && !(((Assignment) output).getSubTasks() == null)) { + System.out.println("\t" + listCount + ". " + output.toString() + priorityLvl); + if (output instanceof Assignment && (((Assignment) output).getSubTasks() != null)) { ArrayList subTasks = ((Assignment) output).getSubTasks(); for (String subtask : subTasks) { System.out.println("\t" + "\t" + "- " + subtask); @@ -498,7 +503,21 @@ public int[] listTagged(String user) throws RoomShareException{ if (belongCount == 0) { throw new RoomShareException(ExceptionType.emptyList); } - int[] done = {belongCount, doneCount}; - return done; + return new int[]{belongCount, doneCount}; + } + + /** + * sets the tasks which are done to an undone state. + * @param index index of task + * @param date date the new deadline of the task + * @throws RoomShareException when the task selected is a Leave + */ + public void reopen(int index, Date date) throws RoomShareException { + tasks.get(index).setDate(date); + CheckAnomaly.checkDuplicate(tasks.get(index)); + if (tasks.get(index) instanceof Meeting) { + CheckAnomaly.checkTimeClash(tasks.get(index)); + } + tasks.get(index).setDone(false); } } diff --git a/src/main/java/Operations/TempDeleteList.java b/src/main/java/Operations/TempDeleteList.java index 4fabec0b44..c4ea54e9fa 100644 --- a/src/main/java/Operations/TempDeleteList.java +++ b/src/main/java/Operations/TempDeleteList.java @@ -11,7 +11,7 @@ public class TempDeleteList { private ArrayList tempDelete; /** - * Constructor for the TempDeleteList Class + * Constructor for the TempDeleteList Class. * Takes in an ArrayList of Task objects as a parameter * @param tempDelete ArrayList of Task objects to be operated on */ @@ -20,7 +20,7 @@ public TempDeleteList(ArrayList tempDelete) { } /** - * Adds a Task to the temporary deleted list + * Adds a Task to the temporary deleted list. * @param task Task that was deleted from the main list and * has to be added into the temp delete list */ @@ -29,7 +29,7 @@ public void add(Task task) { } /** - * Restores a Task from the temp delete list into the main list + * Restores a Task from the temp delete list into the main list. * ALso removes the Task from the temp delete list * if index is not valid, will show the temp delete list to help the * user see the deleted items @@ -49,7 +49,7 @@ public void restore(int index, TaskList taskList) throws RoomShareException { } /** - * lists the tasks in the temp delete list + * lists the tasks in the temp delete list. * @throws RoomShareException when the list is empty */ public void list() throws RoomShareException { @@ -59,9 +59,9 @@ public void list() throws RoomShareException { int listCount = 1; for (Task output : tempDelete) { System.out.println("\t" + listCount + ". " + output.toString()); - if( output instanceof Assignment && !(((Assignment) output).getSubTasks() == null) ) { + if (output instanceof Assignment && (((Assignment) output).getSubTasks() != null)) { ArrayList subTasks = ((Assignment) output).getSubTasks(); - for(String subtask : subTasks) { + for (String subtask : subTasks) { System.out.println("\t" + "\t" + "-" + subtask); } } diff --git a/src/main/java/Operations/Ui.java b/src/main/java/Operations/Ui.java index eb934adcb9..ae485f3c69 100644 --- a/src/main/java/Operations/Ui.java +++ b/src/main/java/Operations/Ui.java @@ -2,7 +2,6 @@ import Enums.SortType; import Enums.TimeUnit; -import Model_Classes.ProgressBar; import java.io.IOException; @@ -17,7 +16,7 @@ public Ui() { } /** - * Shows the startup logo for RoomShare + * Shows the startup logo for RoomShare. */ public void startUp() { String logo = " &@\n" @@ -39,85 +38,85 @@ public void startUp() { } - public void helpAdd() { + void helpAdd() { System.out.println("Adds a Meeting or Assignment to the list\n"); System.out.println("You must specify the description, type of task, and time of the task"); System.out.println("Each field has a particular format of entry\n"); - System.out.println("Type of task must be either meeting or assignment, wrapped in '#'\n" + - "\te.g #meeting# # assignment#\n"); - System.out.println("Description must be wrapped in parentheses\n " + - "\te.g (description)\n"); - System.out.println("Priority must be either high medium or low, wrapped in asterisks '*'\n " + - "\te.g *low*\n"); - System.out.println("Time must be specified, wrapped in '&'\n" + - "\te.g &22/12/2019 18:00& &this friday 13:00& &next monday 14:00& &tmr 16:00&\n"); + System.out.println("Type of task must be either meeting or assignment, wrapped in '#'\n" + + "\te.g #meeting# # assignment#\n"); + System.out.println("Description must be wrapped in parentheses\n " + + "\te.g (description)\n"); + System.out.println("Priority must be either high medium or low, wrapped in asterisks '*'\n " + + "\te.g *low*\n"); + System.out.println("Time must be specified, wrapped in '&'\n" + + "\te.g &22/12/2019 18:00& &this friday 13:00& &next monday 14:00& &tmr 16:00&\n"); System.out.println("If time isn't specified, then the duration of the task must at least be specified\n"); System.out.println("Duration can be specified by wrapping in '^', in terms of number of hours or number of minutes"); System.out.println("\te.g ^2 hours^ ^1 minutes^\n"); - System.out.println("Recurrence of the task can be specified by wrapping either days, weeks or months" + - "\nin '%'\n\te.g %day% %week% %month%\n"); - System.out.println("Task can also be assigned to a name, by wrapping the name in '@'\n" + - "\te.g @Alice@\n"); + System.out.println("Recurrence of the task can be specified by wrapping either days, weeks or months" + + "\nin '%'\n\te.g %day% %week% %month%\n"); + System.out.println("Task can also be assigned to a name, by wrapping the name in '@'\n" + + "\te.g @Alice@\n"); System.out.println("You must specify the task type, description, and either time or duration"); System.out.println("The rest of the fields can still be changed later using other commands"); } - public void helpDelete() { + void helpDelete() { System.out.println("Deletes the tasks in the index or the specified range"); System.out.println("\te.g delete 1"); System.out.println("\te.g delete 3 - 5"); } - public void helperList() { + void helperList() { System.out.println("Shows the list of task that are currently in the Task list"); System.out.println("\teg. list"); } - public void helpDone() { + void helpDone() { System.out.println("Marks the specified task as done/completed"); System.out.println("\teg. done 1"); System.out.println("\teg. done 2 - 4"); } - public void helpRestore() { + void helpRestore() { System.out.println("Restores a deleted task back into the task list based on its index"); System.out.println("\teg. restore 2"); } - public void helpFind() { + void helpFind() { System.out.println("Finds tasks in the task list based on keyword specified"); System.out.println("\teg. find maths"); System.out.println("\treturns all tasks that contains the 'maths' keyword"); } - public void helpPriority() { + void helpPriority() { System.out.println("Changes the priority of the specified task"); System.out.println("\t3 levels of priority: 1 (High), 2 (Medium), 3 (Low)"); System.out.println("\teg. priority 1"); System.out.println("\tThis changes the priority of the task to high"); } - public void helpSnooze() { + void helpSnooze() { System.out.println("Snoozes a task for a specified amount of time"); System.out.println("Different time units include: hours, minutes"); System.out.println("\teg. snooze 1 2 hours"); System.out.println("\tThis snoozes task 1 for a period of 2 hours"); } - public void helpReorder() { + void helpReorder() { System.out.println("Reorder 2 different tasks in the task list"); System.out.println("\teg. reorder 1 - 3"); System.out.println("\tThis will swap the order task 1 and task 3"); } - public void helpSubtask() { + void helpSubtask() { System.out.println("Adds subtasks to an assignment task type"); System.out.println("\teg. subtask 3 subtask1, subtask2"); System.out.println("\tThis will add 2 subtasks to the task at index 3, subtask1 and subtask2"); } - public void helpUpdate() { + void helpUpdate() { System.out.println("Updates the task details"); System.out.println("Fields that are updatable: "); System.out.println("\tDescription: (new_description)"); @@ -128,13 +127,13 @@ public void helpUpdate() { System.out.println("\tAssignee: @joel@"); } - public void helpSort() { + void helpSort() { System.out.println("Sorts the tasks in the task list based on, deadline, priority and alphabetical order"); System.out.println("\teg. sort deadline"); System.out.println("\tThis will sort the tasks in the task list by their deadlines"); } - public void helpLog() { + void helpLog() { System.out.println("Logs the current task list into a saved file"); } @@ -145,14 +144,16 @@ public void helpLog() { */ public void showDeleted(int[] index) { - if (index.length == 1) + if (index.length == 1) { System.out.println("Deleted task number " + (index[0] + 1) + "!"); - else + } + else { System.out.println("Deleted task number " + (index[0] + 1) + " to " + (index[1] + 1) + " !"); + } } /** - * Tells the user that the search operation is executing + * Tells the user that the search operation is executing. */ public void showFind() { System.out.println("Searching for item in task list..."); @@ -166,23 +167,23 @@ public void showDone() { } /** - * tells the user that a task has been added into the list + * tells the user that a task has been added into the list. */ public void showAdd() { System.out.println("Your task has been added into the list!"); } /** - * tells the user goodbye + * tells the user goodbye. */ public void showBye() { System.out.println("Goodbye!"); } /** - * tells the user that RoomShare is listing the tasks + * tells the user that RoomShare is listing the tasks. */ - public void showList() { + void showList() { System.out.println("Listing tasks in your task list..."); } @@ -192,7 +193,7 @@ public void showList() { public void showCommandError() { System.out.println("Sorry, I don't understand this command..."); System.out.println("Try type \"help add\" for instructions on how to add new task"); - System.out.println(" Type list, find, done, delete to perform operations on your todo list"); + System.out.println("\tType list, find, done, delete to perform operations on your todo list"); } /** @@ -235,33 +236,23 @@ public void showReordering() { System.out.println("Reordering the task list..."); } - public void helpList() { + void helpList() { System.out.println("Here are a list of commands you can input: " + - "\n add " + - "\n delete " + - "\n list " + - "\n done " + - "\n restore " + - "\n find " + - "\n priority " + - "\n snooze " + - "\n reorder " + - "\n subtask " + - "\n update " + - "\n sort " + - "\n bye " + - "\n completed " + - "\n overdue " + - "\n reschedule " + - "\n log \n" + - "For more information about a specific command you can \nEnter help followed by a command, eg. help add"); + "\n add " + "\n delete " + "\n list " + "\n done " + + "\n restore " + "\n find " + "\n priority " + + "\n snooze " + "\n reorder " + "\n subtask " + + "\n update " + "\n sort " + "\n bye " + + "\n completed " + "\n overdue " + "\n reschedule " + + "\n log \n" + + "For more information about a specific command you can " + + "\nEnter help followed by a command, eg. help add"); } /** - * Show the message of an error encountered + * Show the message of an error encountered. * @param e the encountered error */ - public void showError(Exception e){ + public void showError(Exception e) { System.out.println(e); } @@ -269,14 +260,10 @@ public void showLogSuccess(String filePath) { System.out.println("Log has been successfully written to " + filePath); } - public void showUpdated (int index) { + public void showUpdated(int index) { System.out.println("Great! I've updated task " + index); } - public static void showProgress(TaskList taskList) { - new ProgressBar(taskList.getSize(), taskList.getDoneSize()).showBar(); - } - public static void clearScreen() throws IOException, InterruptedException { new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); } @@ -289,13 +276,13 @@ public void showChangeInPriority(SortType sortType) { System.out.println("Your sorting preferences have been set to " + sortType.toString()); } - public void showSort() { + void showSort() { System.out.print("sort: "); - if( TaskList.getSortType().equals(SortType.priority) ) { + if (TaskList.getSortType().equals(SortType.priority)) { System.out.println("Priority"); - } else if( TaskList.getSortType().equals(SortType.alphabetical) ) { + } else if (TaskList.getSortType().equals(SortType.alphabetical)) { System.out.println("Alphabetical"); - } else if( TaskList.getSortType().equals(SortType.deadline) ){ + } else if (TaskList.getSortType().equals(SortType.deadline)) { System.out.println("Deadline"); } else { System.out.println("Type"); @@ -307,23 +294,23 @@ public void showRestoreList() { } public void showOverdueList() { - System.out.println("Here are your overdued tasks: "); + System.out.println("Here are your overdue tasks: "); } - public void helpBye() { + void helpBye() { System.out.println("Typing in 'bye' will exit the program"); } - public void helpCompleted() { + void helpCompleted() { System.out.println("Shows the list of completed tasks"); } - public void helpOverdue() { - System.out.println("Shows the list of overdued tasks"); + void helpOverdue() { + System.out.println("Shows the list of overdue tasks"); } - public void helpReschedule() { - System.out.println("Reschedules an overdued task by index to a later date by inputting a new date"); + void helpReschedule() { + System.out.println("Reschedules an overdue task by index to a later date by inputting a new date"); System.out.println("\teg. reschedule 1 &20/11/2019 10:00&"); System.out.println("This will reschedule task 1 in the overdue task list to have a deadline of 20th Nov 2019 at 10am"); } @@ -337,4 +324,8 @@ public void showTaggedPercentage(String user) { public void showDeletedList() { System.out.println("Here are the tasks that you have deleted and are in temporary storage"); } + + public void showDoneList() { + System.out.println("These are the tasks that you have already done:"); + } } diff --git a/src/main/java/Operations/subTaskCreator.java b/src/main/java/Operations/subTaskCreator.java index c16ccb0dcb..633740e3ba 100644 --- a/src/main/java/Operations/subTaskCreator.java +++ b/src/main/java/Operations/subTaskCreator.java @@ -8,7 +8,7 @@ public class subTaskCreator { /** - * creates sub tasks for Assignments. Appends the information to the Assignment class + * creates sub tasks for Assignments. Appends the information to the Assignment class. * checks for duplicate subTasks * throws RoomShareException if there are mistakes in the formatting of sub tasks * @param index index of the task to add sub tasks to @@ -22,27 +22,27 @@ public subTaskCreator(int index, String subTasks) throws RoomShareException { ArrayList subtasks = new ArrayList<>(); - for( int i=0; i date = taskCreator.extractDate(userInput); + taskList.reopen(index,date.get(0)); + } catch (RoomShareException e) { + ui.showError(e); + } + storage.writeFile(TaskList.currentList(), "data.txt"); + storage.writeFile(OverdueList.getOverdueList(), "overdue.txt"); + listRoutine.list(); + break; + default: Ui.clearScreen(); ui.startUp(); diff --git a/src/test/java/CheckAnomalyTest.java b/src/test/java/CheckAnomalyTest.java index dc99c9d6a5..1fabf76768 100644 --- a/src/test/java/CheckAnomalyTest.java +++ b/src/test/java/CheckAnomalyTest.java @@ -21,13 +21,13 @@ public class CheckAnomalyTest { static { try { - at1 = parser.formatDateCustom_1("12/12/2019 17:00"); - at2 = parser.formatDateCustom_1("12/12/2019 19:00"); - at3 = parser.formatDateCustom_1("12/12/2019 10:00"); - at4 = parser.formatDateCustom_1("12/12/2019 09:00"); - at5 = parser.formatDateCustom_1("21/12/2019 13:00"); - at6 = parser.formatDateCustom_1("22/12/2019 13:00"); - at7 = parser.formatDateCustom_1("25/12/2019 13:00"); + at1 = parser.formatDateDDMMYY("12/12/2019 17:00"); + at2 = parser.formatDateDDMMYY("12/12/2019 19:00"); + at3 = parser.formatDateDDMMYY("12/12/2019 10:00"); + at4 = parser.formatDateDDMMYY("12/12/2019 09:00"); + at5 = parser.formatDateDDMMYY("21/12/2019 13:00"); + at6 = parser.formatDateDDMMYY("22/12/2019 13:00"); + at7 = parser.formatDateDDMMYY("25/12/2019 13:00"); taskList = new TaskList(storage.loadFile("test.txt")); meeting1 = new Meeting("test1", at1, 2, TimeUnit.hours); meeting2 = new Meeting("test2", at2); diff --git a/src/test/java/subTaskCreatorTest.java b/src/test/java/subTaskCreatorTest.java index 79d4fe447f..eac7242fac 100644 --- a/src/test/java/subTaskCreatorTest.java +++ b/src/test/java/subTaskCreatorTest.java @@ -4,8 +4,6 @@ import Operations.subTaskCreator; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.Arrays; import java.util.Date; import static org.junit.jupiter.api.Assertions.*; @@ -20,7 +18,7 @@ class subTaskCreatorTest { static { try { taskList = new TaskList(storage.loadFile("test.txt")); - by = parser.formatDateCustom_1("12/12/2019 17:00"); + by = parser.formatDateDDMMYY("12/12/2019 17:00"); assignment = new Assignment("test", by); taskList.add(assignment); new subTaskCreator(3, "one,two");