Write a program in Java that:Short Description: Creating an object oriented (als
ID: 3885742 • Letter: W
Question
Write a program in Java that:Short Description: Creating an object oriented (also referred to as OO) program that helps a user build and manage a “to do” list. At a very minimum you will need to create three classes o a starting point – the main and anything used for the basic flow of the program o ToDoEntry – holds information and functionality about a single to do list entry Priority and description o ToDoList – all functionality related around managing a list of to do entries. This class should not include any communication with the user other than reporting errors. You cannot use the key word static anywhere in your program except for the main. Long Description: In an object oriented design, important data structures are encapsulated in classes. The client code instantiates objects and then communicates with these objects via their public interfaces (“methods”). It has no access to their private implementations. At run time, an object oriented system is often viewed as an intercommunicating network of objects and client code. When the program is run it reads a text file; to_do.txt. If the file is empty or the file name does not exist, the program starts with an empty “to do” list. Otherwise, it attempts to open the file and, if successful, creates a “to do” list of the items in the file. Example, to_do.txt might look like: 1 finish COMP 2503 assignment 1 2 pay overdue MasterCard bill 2 do laundry 3 drink 2 buy groceries 1 make dentist appointment The integer at the beginning of a line is the item’s priority (3 = high, 2 = medium and 1= low). If the integer value is not 1, 2 or 3, then it defaults to a value of 1 (low). Page 2 of 5 If any errors occur when reading information on a line (i.e., missing the priority integer or missing description) output an error message to the console and the entire line that was wrong and continue to the next line in the file. When the program quits, it writes information to out.txt. If this file exists, then it is overwritten. Otherwise, a new file is created and all information is written out. The output format must match the input format (to_do.txt) for the program as shown above. The current list will be written out using the following format: 3 drink 2 pay overdue MasterCard bill 2 do laundry 2 buy groceries 1 finish COMP 2503 assignment 1 1 make dentist appointment Once the initial “to do” list has been read, the program will read the commands from cmd.txt repeatedly until no more commands are left in the file. You can assume that there will be no errors in the cmd.txt file. The cmd.txt can contain four different commands: d (display), a (add), r (remove), and u (update). An example cmd.txt might look like: d a h phone Aunt to wish her happy birthday r 2 u 4 h d Each of the four commands are explained below using the example from to_do.txt discussed above. The “d” command, i.e. “display” will display the current list to the screen using the following format: High Priority: 1: - drink Medium Priority: 2: - pay overdue MasterCard bill 3: - do laundry 4: - buy groceries Low Priority: 5: - finish COMP 2503 assignment 1 6: - make dentist appointment Note that the list items are numbered. These numbers will play a part in the “remove” and “update” commands. Page 3 of 5 The “a” command (i.e., “add”) will be in the following format in the cmd.txt file: a h phone Aunt to wish her happy birthday In the above example, “a” is the command for add, followed by a single character for the priority (h / m / l) and then followed by the description. The new list item must be added at the end of the sub-list of the given priority. For example, if the display command was re-executed after the above “a” command is completed, it would display the following: High Priority: 1: - drink 2: - phone Aunt to wish her happy birthday Medium Priority: 3: - pay overdue MasterCard bill 4: - do laundry 5: - buy groceries Low Priority: 6: - finish COMP 2503 assignment 1 7: - make dentist appointment Notice we have a second entry under high priority and the list numbers have been updated to accommodate this. The “r”, “remove” command behaves as follows: r 4 d Here, “r” is remove, and 4 is the item number in the display list. In our most recent example, “do laundry” is the item to be removed. Now, “d” will display the list after removing item 4: High Priority: 1: - drink 2: - phone Aunt to wish her happy birthday Medium Priority: 3: - pay overdue MasterCard bill 4: - buy groceries Low Priority: 5: - finish COMP 2503 assignment 1 6: - make dentist appointment Notice the previous list item #4 “do laundry” is removed and the list numbers have once again been updated accordingly. Page 4 of 5 The “u” or the “update” command allows users to change the priority of a given item. For example, if the user suddenly realizes that the assignment is due soon, then the command read will be: u 5 h d Here, “u” stands for update, 5 is the item number and “h” is the new priority. After the update, the list will be displayed as follows: High Priority: 1: - drink 2: - phone Aunt to wish her happy birthday 3: - finish COMP 2503 assignment 1 Medium Priority: 4: - pay overdue MasterCard bill 5: - buy groceries Low Priority: 6: - make dentist appointment Notice that the entry “finish COMP 2503 assignment 1” is now listed at the end of the high priority section. Once the command file has been read, the program will write the “to do” list to a text file called “out.txt”. Below is a sample of the output file for our example after the cmd.txt is executed: 3 drink 3 phone Aunt to wish her happy birthday 3 finish COMP 2503 assignment 1 2 pay overdue MasterCard bill 2 buy groceries 1 make dentist appointment
Explanation / Answer
ToDoDriver.java
import java.util.*;
import java.io.*;
public class ToDoDriver {
public static void main(String[] args)
{
String filename; // used for the filename console input
String command; // used for the menu console input
String description;
String priorityString;
int priorityInt = 0;
ToDoEntry entry;
ToDoList list;
ToDoEntry tempEntry;
int nextInt = 0;
String indexString;
int index = 0;
String confirm;
// prompt user for a file name
System.out.print("Enter a filename: ");
Scanner inputFromConsole = new Scanner(System.in);
filename = inputFromConsole.nextLine();
System.out.println("Opening: " + filename);
// open a file and if successful process contents
list = new ToDoList(); //create an empty list..
try
{
Scanner fileContents = new Scanner(new File(filename));
while (fileContents.hasNextLine()) //loops for the entire file
{
// check if you can read an Int, if not skip and print error
if (fileContents.hasNextInt())
{
nextInt = fileContents.nextInt();
if (nextInt > 0 && nextInt < 4) // valid integer?
{
entry = new ToDoEntry(nextInt, fileContents.nextLine().trim());
list.add(entry);
}
else
System.out.println("ERROR - Line Not Valid. Integer Not in Valid Range (" + nextInt + fileContents.nextLine() + ").");
}
else
System.out.println("ERROR - Line Not Valid (" + fileContents.nextLine() + ").");
}
fileContents.close(); //close file reader stream
}
catch (FileNotFoundException e)
{
System.out.println("ERROR - filename: " + e.getMessage());
}
// regardless if the file is loaded or not, start menu.
do
{
System.out.println(" To Do list Manager: ");
System.out.println("d) display list");
System.out.println("a) add item");
System.out.println("r) remove item");
System.out.println("u) update item");
System.out.println("q) quit ");
System.out.print("Choice: ");
command = inputFromConsole.nextLine();
switch(command)
{
// Just Display the List - like a rabid dog
case "d":
list.display();
break;
// Create a ToDoEntry object, and add it to the list
case "a":
System.out.print("Describe new item: ");
description = inputFromConsole.nextLine().trim();
// check if priority is h/m/l
do
{
System.out.print("Enter priority (h/m/l): ");
priorityString = inputFromConsole.nextLine();
if (!(priorityString.equals("h") || priorityString.equals("m") || priorityString.equals("l")))
System.out.println("ERROR - invalid priority (" + priorityString + "). Please try again.");
} while (!(priorityString.equals("h") || priorityString.equals("m") || priorityString.equals("l")));
// convert priorityString to priorityInt (String to Integer Conversion)
switch(priorityString)
{
case "h":
priorityInt = 3;
break;
case "m":
priorityInt = 2;
break;
case "l":
priorityInt = 1;
break;
default:
priorityInt = 0;
break;
}
// add new item to the list
entry = new ToDoEntry(priorityInt, description);
list.add(entry);
break;
// remove an item given the index
case "r":
// check if item number is a valid integer
System.out.print("Enter item number: ");
indexString = inputFromConsole.nextLine();
// converts a string to an int, if valid removes the item at index, else throws and exception
try
{
tempEntry = null;
index = Integer.parseInt(indexString); //check if String can be an Integer, then convert it
// lookup if index exists...
tempEntry = list.lookup(index);
// index exists, now begin to remove it
if (tempEntry != null)
{
// make sure the confirmation is y or n
do
{
System.out.print("Remove "" + tempEntry + "" (y/n)? ");
confirm = inputFromConsole.nextLine();
if (!(confirm.equals("y") || confirm.equals("n")))
System.out.println("ERROR - invalid confirmation (" + confirm + "). Please try again.");
} while (!(confirm.equals("y") || confirm.equals("n")));
if (confirm.equals("y"))
list.remove(index);
}
else
System.out.println("ERROR - Index out of bounds (" + index + ").");
}
catch (NumberFormatException e)
{
System.out.println("ERROR - Not a valid Integer (" + indexString + ").");
}
break;
// update a given object command
case "u":
// check if item number is a valid integer
System.out.print("Enter item number: ");
indexString = inputFromConsole.nextLine();
// converts a string to an integer, if valid removes the item at index, else throws and exception
try
{
tempEntry = null;
index = Integer.parseInt(indexString);
// lookup if index exists...
tempEntry = list.lookup(index);
// index exists, now begin to remove it
if (tempEntry != null)
{
// make sure the confirmation is y or n
do
{
System.out.print("Update "" + tempEntry + "" (y/n)? ");
confirm = inputFromConsole.nextLine();
if (!(confirm.equals("y") || confirm.equals("n")))
System.out.println("ERROR - invalid confirmation (" + confirm + "). Please try again.");
} while (!(confirm.equals("y") || confirm.equals("n")));
// Remove the old ToDoEntry object, and re-add it to the new priority list
if (confirm.equals("y"))
{
list.remove(index);
// Update the object now
do
{
System.out.print("Enter priority (h/m/l): ");
priorityString = inputFromConsole.nextLine();
if (!(priorityString.equals("h") || priorityString.equals("m") || priorityString.equals("l")))
System.out.println("ERROR - invalid priority (" + priorityString + "). Please try again.");
} while (!(priorityString.equals("h") || priorityString.equals("m") || priorityString.equals("l")));
// convert priorityString to priorityInt (String to Int Conv)
switch(priorityString)
{
case "h":
priorityInt = 3;
break;
case "m":
priorityInt = 2;
break;
case "l":
priorityInt = 1;
break;
default:
priorityInt = 0;
break;
}
// add new item to the list
entry = new ToDoEntry(priorityInt, tempEntry.toString());
list.add(entry);
}
}
else
System.out.println("ERROR - Index out of bounds (" + index + ").");
}
catch (NumberFormatException e)
{
System.out.println("ERROR - Not a valid Integer (" + indexString + ").");
}
break;
// quit the program gracefully
case "q":
// prompt the user for a filename
System.out.print("Quitting Program. Enter your filename: ");
filename = inputFromConsole.nextLine();
System.out.println("Writing: " + filename);
try
{
PrintStream outFile = new PrintStream(new FileOutputStream(filename));
// writing files...
for (index = 1; index <= list.size(); index++) //index has been declared above.
{
tempEntry = list.lookup(index);
// don't print out an extra blank line
if (index < list.size())
outFile.println(tempEntry.printFriendly());
else
outFile.print(tempEntry.printFriendly());
}
outFile.close(); // close the print stream
System.out.println("The file has been created! You can view it by opening: " + filename);
}
catch (FileNotFoundException e)
{
System.out.println("ERROR - unable to open/create a new file with the given filename: " + e.getMessage());
command = "error"; // if file is not created/opened, rerun the menu
}
break;
// display error if command is not correct
default:
System.out.println("ERROR - Invalid Command (" + command + "). Try Again.");
break;
}
} while (!command.equals("q"));
inputFromConsole.close(); //close console input stream
}
}
ToDoEntry.java
public class ToDoEntry
{
private int priorityLevel;
private String description;
/**
* Default constructor uses ToDoEntry with two parameters
*/
public ToDoEntry()
{
this(0, ""); //use ToDoEntry Constructor with parameters
}
/**
* constructor used to set up basic information about the todo entry
* @param priority the priority of the entry
* @param description the description of what the to do entry is
*/
public ToDoEntry(int priority, String description)
{
this.priorityLevel = priority;
this.description = description; //using this.() for instance variable access
}
/**
* Concerts the object into a string representation
* @return description returns the string representation of the object
*/
public String toString()
{
return description;
}
/**
* Prints out priority level and description
* @return description returns a string composed of priorityLevel and description
*/
public String printFriendly()
{
// convert the integer toString
return "" + priorityLevel + " " + description;
}
/**
* Getter for the object's priority level
* @return priorityLevel returns the objects current priority
*/
public int getPriorityLevel()
{
return priorityLevel;
}
}
ToDoList.java
import java.util.*;
public class ToDoList
{
// three lists, ranging priorities.
private ArrayList<ToDoEntry> highPriorityList = new ArrayList<ToDoEntry>();
private ArrayList<ToDoEntry> mediumPriorityList = new ArrayList<ToDoEntry>();
private ArrayList<ToDoEntry> lowPriorityList = new ArrayList<ToDoEntry>();
/**
* displays the list to the given console output stream
*/
public void display()
{
int sizeOfHigh = highPriorityList.size();
int sizeOfMedium = mediumPriorityList.size();
int sizeOfLow = lowPriorityList.size();
int index = 1; //running count index thats shared amongst all priority lists
System.out.println("High Priority ");
for (int iterator = 0; iterator < sizeOfHigh; iterator++)
{
System.out.println(index + ": - " + highPriorityList.get(iterator));
index++;
}
System.out.println(" Medium Priority ");
for (int iterator = 0; iterator < sizeOfMedium; iterator++)
{
System.out.println(index + ": - " + mediumPriorityList.get(iterator));
index++;
}
System.out.println(" Low Priority ");
for (int iterator = 0; iterator < sizeOfLow; iterator++)
{
System.out.println(index + ": - " + lowPriorityList.get(iterator));
index++;
}
}
/**
* passes back the given entry and the location
* @param index the location of the entry
* @return tempEntry the entry object if found, null if it was out of bounds
*/
public ToDoEntry lookup(int index)
{
ToDoEntry tempEntry = null;
int sizeOfHigh = highPriorityList.size();
int sizeOfMedium = mediumPriorityList.size();
int sizeOfLow = lowPriorityList.size();
if (isInBounds(index))
{
// check index at each priority level
if (index <= sizeOfHigh)
{
tempEntry = highPriorityList.get(index-1);
}
else if ((index - sizeOfHigh) <= sizeOfMedium)
{
index -= sizeOfHigh;
tempEntry = mediumPriorityList.get(index-1);
} else if ((index - (sizeOfHigh + sizeOfMedium)) <= sizeOfLow)
{
index -= (sizeOfHigh + sizeOfMedium);
tempEntry = lowPriorityList.get(index-1);
}
}
return tempEntry;
}
/**
* removes the item with the given position number (if possible)
* @param index the index of object
*/
public void remove(int index)
{
ToDoEntry tempEntry = null;
tempEntry = lookup(index);
if (tempEntry != null)
{
// add ToDoEntry to the proper list
switch(tempEntry.getPriorityLevel())
{
case 1:
lowPriorityList.remove(tempEntry);
break;
case 2:
mediumPriorityList.remove(tempEntry);
break;
case 3:
highPriorityList.remove(tempEntry);
break;
}
}
}
/**
* adds an item with the given description and priority
* @param entry the ToDoList Entry object to add
*/
public void add(ToDoEntry entry)
{
// add ToDoEntry to the proper list
switch(entry.getPriorityLevel())
{
case 1:
lowPriorityList.add(entry);
break;
case 2:
mediumPriorityList.add(entry);
break;
case 3:
highPriorityList.add(entry);
break;
}
}
/**
* Gives the size of the three priority lists together
* @return Integer the number of entries currently in the list
*/
public int size()
{
return highPriorityList.size() + mediumPriorityList.size() + lowPriorityList.size();
}
/**
* Determines if the index is within the bounds of the list
* @param index the index to check
* @return Boolean true if within, false otherwise
*/
private boolean isInBounds(int index)
{
// index starts at 1
return ( index > 0 && index <= size() );
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.