The purpose of this assignment is to use exceptions, objects, and text file inpu
ID: 3723419 • Letter: T
Question
The purpose of this assignment is to use exceptions, objects, and text file input and file output. The application will allow the user to enter data about purchases and store that data in a text file.
Create an Eclipse project named ManagePurchases. Use a package name of edu.seattlesate.managepurchases. This project will have 3 classes – Purchases, ManagePurchases, and IllegalPurchaseArgumentException. The ManagePurchases class will have the main method. Each class must be public and in its .java own file.
The following requirements apply to the IllegalPurchaseArgumentException class.
Make this a checked exception by extending the Exception class
Create two constructors as indicated in the UML class diagram (IllegalPurchaseArgumentException Class DiagramPreview the document). Each constructor must call the superclass constructor passing the appropriate error message.
The following requirements apply to the Purchase class.
Create four private instance variables. Use a String to represent the product name. Use a String to represent the store where the product was purchased. Use a LocalDate to represent the date of the purchase. Use a double to represent the product's cost.
Create a public get and set method for each private variable.
Create a single constructor that has four parameters, one for each private variable.
Implement the following edits: the product name cannot be null nor can it have a length less than one; the store name cannot be null nor can it have a length less than one; the purchase date cannot be null; the cost must be greater than or equal to zero. Throw an IllegalPurchaseArgumentException if any of the values are invalid.
Create a toString method that displays the class name and the values of each of the four instance variables. Below is sample output from the toString method. (Note: Your browser may display this output on one or more lines. Code it without line breaks.)
class edu.seattlestate.managepurchases.Purchase [productName=Bread, storeName=Krogetr Store 111, purchaseDate=2014-03-13, cost=1.99]
The following requirements apply to the ManagePurchase application class.
This class will have the main method. Create an ArrayList to store Purchase objects.
Display a menu that has choices for: 1 - Add a purchase; 2 - Display all purchases; 3 - Exit. Display an error message and repeat the menu if some other value is entered. Catch an exception if letters instead of numbers are entered.
When the user chooses menu option 1, prompt for a product name, a store name, purchase date, and a cost. Edit these values such that: the product name cannot have a length less than one; the store name cannot have a length less than one; the purchase date cannot be null; the cost cannot be less than zero. If the data is valid, create a Purchase object and store it in the ArrayList. If the data is invalid prompt the user to re-enter valid data. You must edit the data the user enters to make sure it is in the proper format. Also use the DateTimeParseException to determine when an invalid date is entered.
When the user chooses menu option 2, display all the Purchase objects in the ArrayList using the toString method of the Purchase class.
When the user chooses menu option 3, check to see if the ArrayList has any Purchase objects in it. If it does, write the data from each object to a text file. Then display the message "Thank you for using the Purchase Tracker" and end the application. The data must be written to a relative file location using the file name purchases.txt. Make this file name a class constant and use the constant in your code wherever necessary (instead of purchases.txt). Use try with resources when writing the file.
When the application first starts check to see if the purchases.txt file exists. If it does, read each piece of data for an object, create the Purchase object, and store the Purchase object into the ArrayList. If the file doesn't exist just continue with an empty ArrayList. Use try with resources when reading the file.
Remember to write the Purchase data as text data to the file. I recommend the following to write the data.
For each Purchase object in the ArrayList, call the get method for the product name and write this as a line to the file; call the get method for store name and write this as a line to the file; call the get method for the purchase date, convert it to a string and write this as a line to the file; call the get method for the cost, convert this to a String, and write this as a line to the file. In this design, each object will create four lines of text data in the output file.
Each set of four lines in the file are required to create a Purchase object. As long as the file has more data to read, read a line and consider this the product name; read the next line and consider this the store name; read the next line and consider this the purchase date; convert this string version of the purchase date to a LocalDate object; read the next line and consider this the cost; convert this String to a double. Use these four pieces of data to instantiate a Purchase object. Put the Purchase object into the ArrayList. Continue processing the next four lines of data from the file, if any.
Use a Scanner object for all user input. Use System.out for all user output. (This doesn't include the file input and output.)
Explanation / Answer
Hello, I have a solution for you. Implemented everything as per the requirements. Defined following things in this answer.
/*
* Purchase.java
*/
package edu.seattlesate.managepurchases;
import java.time.LocalDate;
public class Purchase {
private String productName;
private String storeName;
private LocalDate dateOfPurchase;
private double productCost;
public Purchase(String productName, String storeName, LocalDate dateOfPurchase, double productCost)
throws IllegalPurchaseArgumentException {
/**
* invoking setter methods so that the exceptions will be thrown if any
* inputs are invalid, we don't have to write the code many times
*/
setProductName(productName);
setStoreName(storeName);
setDateOfPurchase(dateOfPurchase);
setProductCost(productCost);
}
/**
* getters and setters
*/
public String getProductName() {
return productName;
}
public void setProductName(String productName) throws IllegalPurchaseArgumentException {
if (productName == null || productName.length() == 0) {
throw new IllegalPurchaseArgumentException("Invalid product name");
}
this.productName = productName;
}
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName) throws IllegalPurchaseArgumentException {
if (storeName == null || storeName.length() == 0) {
throw new IllegalPurchaseArgumentException("Invalid store name");
}
this.storeName = storeName;
}
public LocalDate getDateOfPurchase() {
return dateOfPurchase;
}
public void setDateOfPurchase(LocalDate dateOfPurchase) throws IllegalPurchaseArgumentException {
if (dateOfPurchase == null) {
throw new IllegalPurchaseArgumentException("Invalid purchase date");
}
this.dateOfPurchase = dateOfPurchase;
}
public double getProductCost() {
return productCost;
}
public void setProductCost(double productCost) throws IllegalPurchaseArgumentException {
if (productCost < 0) {
throw new IllegalPurchaseArgumentException("Invalid product cost");
}
this.productCost = productCost;
}
// returns a string containing all data
public String toString() {
return String.format("%s [productName=%s, storeName=%s, purchaseDate=%s, cost=%.2f]",
getClass().toString(), productName, storeName, dateOfPurchase, productCost);
}
}
/*
* ManagePurchases.java
*/
package edu.seattlesate.managepurchases;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Scanner;
public class ManagePurchases {
static ArrayList<Purchase> purchasesList;
static Scanner scanner;
/*update the data file path with your data file path name. It is important */
static final File dataFile = new File("C:\Users\user\Documents\NetBeansProjects\CurrencyConverter\src\edu\seattlesate\managepurchases\purchases.txt");
public static void main(String[] args) {
purchasesList = new ArrayList<Purchase>();
scanner = new Scanner(System.in);
checkForExistingData();
int choice = 0;
/*loops until user chooses to quit*/
while (choice != 3) {
choice = displayMenuReturnChoice();
switch (choice) {
case 1:
addPurchase();//adding a purchase
System.out.println("Product added successfully!");
break;
case 2:
display(); //displaying all purchases
break;
case 3:
saveToFile();//saving to the file and quit
System.out.println("Thank you for using the Purchase Tracker");
break;
}
}
}
/**
* method to display the menu and return user choice
* @return 1,2 or 3
*/
static int displayMenuReturnChoice() {
int choice;
System.out.println("1 - Add a purchase; 2 - Display all purchases; 3 - Exit.");
System.out.println("## Enter your choice: ");
try {
choice = Integer.parseInt(scanner.nextLine());
if (choice < 1 || choice > 3) {
System.out.println("Invalid choice, try again...");
return displayMenuReturnChoice();
} else {
return choice;
}
} catch (NumberFormatException nfe) {
System.out.println("Invalid input, try again...");
return displayMenuReturnChoice();
}
}
/**
* method to prompt the user for input, validate the input, create a
* Purchase object and add it to the list
*
* @return true once everything is done properly
*/
static boolean addPurchase() {
try {
String productName = null, storeName = null;
double cost = 0;
LocalDate date = null;
boolean done = false;
/**
* Loops until each field is properly inputted
*/
while (!done) {
System.out.println("Enter product name: ");
productName = scanner.nextLine();
if (productName.length() == 0) {
System.out.println("Invalid product name, try again...");
} else {
done = true;
}
}
done = false;
while (!done) {
System.out.println("Enter store name: ");
storeName = scanner.nextLine();
if (storeName.length() == 0) {
System.out.println("Invalid store name, try again...");
} else {
done = true;
}
}
done = false;
while (!done) {
System.out.println("Enter date of purchase:(yyyy-mm-dd) ");
date = LocalDate.parse(scanner.nextLine());
if (date == null) {
System.out.println("Invalid date, try again...");
} else {
done = true;
}
}
done = false;
while (!done) {
System.out.println("Enter cost: ");
cost = Double.parseDouble(scanner.nextLine());
if (cost < 0) {
System.out.println("Invalid cost, try again...");
} else {
done = true;
}
}
/**
* Creating a purchase object with valid input , and adding to the list
*/
Purchase p = new Purchase(productName, storeName, date, cost);
purchasesList.add(p);
return true;
} catch (NumberFormatException nfe) {
System.out.println("Invalid input, try again...");
return addPurchase();
} catch (DateTimeParseException d) {
System.out.println("Invalid date, try again...");
return addPurchase();
} catch (IllegalPurchaseArgumentException ex) {
System.out.println(ex.getMessage());
return addPurchase();
}
}
/**
* method to display all the purchases
*/
static void display() {
if (purchasesList != null) {
System.out.println("===Purchases List===");
for (Purchase p : purchasesList) {
System.out.println(p);
}
}
}
/**
* method to save data to the file once done all operations
*/
static void saveToFile() {
if (purchasesList != null && purchasesList.size() > 0) {
try {
PrintWriter writer = new PrintWriter(dataFile);
/**
* Appending each field line by line
*/
for (Purchase p : purchasesList) {
writer.append(p.getProductName() + " ");
writer.append(p.getStoreName() + " ");
writer.append(p.getDateOfPurchase() + " ");
writer.append(p.getProductCost() + " ");
}
writer.close();
} catch (FileNotFoundException ex) {
System.out.println("Error while saving data!");
}
}
}
/**
* method to check if the data file exist when the program is loaded, if yes, loading
* the contents into the array list, (if any)
*/
static void checkForExistingData(){
if(dataFile.exists() && dataFile.length()>0){
try {
Scanner fileScanner=new Scanner(dataFile);
while(fileScanner.hasNext()){
String productName=fileScanner.nextLine().trim();
String storeName=fileScanner.nextLine().trim();
LocalDate date=LocalDate.parse(fileScanner.nextLine().trim());
double cost=Double.parseDouble(fileScanner.nextLine());
Purchase p=new Purchase(productName, storeName, date, cost);
purchasesList.add(p);
}
System.out.println("Existing data has been loaded to the list");
} catch (FileNotFoundException ex) {
System.out.println("Input data file not found!");
} catch(Exception e){
System.out.println("Corrupted data file!");
}
}
}
}
/*
* IllegalPurchaseArgumentException.java
*/
package edu.seattlesate.managepurchases;
public class IllegalPurchaseArgumentException extends Exception{
public IllegalPurchaseArgumentException() {
super("Illegal Values Provided");
}
public IllegalPurchaseArgumentException(String msg) {
super(msg); //passing exception to the super class constructor
}
}
/*OUTPUT*/
1 - Add a purchase; 2 - Display all purchases; 3 - Exit.
## Enter your choice:
x
Invalid input, try again...
1 - Add a purchase; 2 - Display all purchases; 3 - Exit.
## Enter your choice:
0
Invalid choice, try again...
1 - Add a purchase; 2 - Display all purchases; 3 - Exit.
## Enter your choice:
1
Enter product name:
Mobile Phone
Enter store name:
MobiStore
Enter date of purchase:(yyyy-mm-dd)
2016-12-01
Enter cost:
200.99
Product added successfully!
1 - Add a purchase; 2 - Display all purchases; 3 - Exit.
## Enter your choice:
2
===Purchases List===
class edu.seattlesate.managepurchases.Purchase [productName=Mobile Phone, storeName=MobiStore, purchaseDate=2016-12-01, cost=200.99]
1 - Add a purchase; 2 - Display all purchases; 3 - Exit.
## Enter your choice:
1
Enter product name:
Laptop
Enter store name:
Oxygen digital store
Enter date of purchase:(yyyy-mm-dd)
2018-01-23
Enter cost:
400.50
Product added successfully!
1 - Add a purchase; 2 - Display all purchases; 3 - Exit.
## Enter your choice:
2
===Purchases List===
class edu.seattlesate.managepurchases.Purchase [productName=Mobile Phone, storeName=MobiStore, purchaseDate=2016-12-01, cost=200.99]
class edu.seattlesate.managepurchases.Purchase [productName=Laptop, storeName=Oxygen digital store, purchaseDate=2018-01-23, cost=400.50]
1 - Add a purchase; 2 - Display all purchases; 3 - Exit.
## Enter your choice:
3
Thank you for using the Purchase Tracker
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.