Start with this java files. ShoppingCart.java, Item.java, ShoppingCartTester.jav
ID: 3726408 • Letter: S
Question
Start with this java files. ShoppingCart.java, Item.java, ShoppingCartTester.java
You will model ShoppingCart as java Class.
ShoppingCart class will store Items in the cart. Item will be another java class. Item is identified by Id attribute. If the Item with the same Id is added multiple times in the cart, change the quantity and DO NOT add multiple Item objects with same Id.
The program should prompt various actions on ShoppingCart
addItemToCart – Two overloads
updateItemQuantity
removeItemFromCart
calculateItemBasedDiscount
getTotalCost
Based on the selected action ask for further input.
For example, if user selects to “addItemToCart”, prompt user to enter
itemId
itemName
itemPrice
itemQuantity
Implement all methods in ShoppingCart.java
Write test in ShoppingCartTester.java. Use scanner to implement userInputSimulator() method. See sample output for sample run.
Before you start working on user input, implement the tester methods as provided in the starter code. Once you have everything working enable the user input and comment out the tester code.
Gracefully exit the program
Sample Output
WELCOME TO SHOPPING CART APPLICATION.
PLEASE ENTER YOUR NAME:
Joe Peters
Welcome Joe Peters. Your Shopping Cart is created.
-----------------------------------------------------------------------------
Select one of the following options:
1. Add Item in ShoppingCart
2. Update Quantity for Item in ShoppingCart
3. Remove Item from Shopping Cart
4. Calculate Item Based Discount
5. Get total cost
6. Exit
1
You have selected to Add Item in Shopping Cart
Please Enter Item Id:
123
Please Enter Item Price:
20.50
Please Enter Item Quantity:
20
Item "Id: 123, Cost: $20.50" is added in ShoppingCart with Quantity 20
Select one of the following options:
1. Add Item in ShoppingCart
2. Update Quantity for Item in ShoppingCart
3. Remove Item from Shopping Cart
4. Calculate Item Based Discount
5. Get total cost
6. Exit
2
You have selected to update Quantity for Item in ShoppingCart
Please Enter Item Id for which you want to change Quantity:
123
Please Enter new Quantity:
25
Quantity for Item "Id: 123, Cost: $20.50" is changed to 25
Select one of the following options:
1. Add Item in ShoppingCart
2. Update Quantity for Item in ShoppingCart
3. Remove Item from Shopping Cart
4. Calculate Item Based Discount
5. Get total cost
6. Exit
6
Are you sure you want to Exit(y/n)?
y
Good Bye Have a Nice Day!
Make sure you create helper methods instead of putting entire testing code in Main method for getting options and calling appropriate function once you receive the options.
Total Possible Points: 100
Program runs as submitted - 5 points
Constructor for ShoppingCart and Item is implemented – 5 points
Program accepts all valid option (1-6) only and handle errors properly - 15 points
Program adds Item to shopping cart (along with check for Id to avoid duplicate items in the cart)- 10 points
Program updates quantity of Item in ShoppingCart - 10 points
Program removes Item from cart - 10 points
Program calculates the discount based on total quantity ACROSS ALL items in the cart - 10 points
Program calculates total cost applying discount - 10 points
Program exits without problems with proper message - 5 points
Code is well documented using Javadocs - 10 points
Program handles errors properly - 10 points
Shows error for user input (validate double, string, char, etc)
Shows error when Item not found for removing an item
Show error for: - user enters negative values for Item Qty and Item Price
----------------------------------------
/**
Order class maintains the Items that are part of the order.
*/
//add package staement here
import java.util.ArrayList;
public class ShoppingCart
{
public static final double LOW_DISCOUNT = 0.10;
public static final double MEDIUM_DISCOUNT = 0.25;
public static final double HIGH_DISCOUNT = 0.50;
ArrayList itemArray = new ArrayList();
private String customerName;
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public ShoppingCart(String customerName){
//implement here
}
public void addItemToCart(Item item, int quanity) {
//If item already exists then update the quantity of that item by calling updateItemQuantity
//If a new item is added, add the item to itemArray and fetch the details of the item added by calling toString() in Item;
//print the fetched string here
//donot display the details here if the item is updated, that should be done inside updateItemQuantity()
}
public void addItemToCart(int itemId, double itemPrice, int itemQuantity) {
//Create Object of Item
//Call addItemToCart(Item item, int quanity)
}
public void updateItemQuantity(int itemID, int newQuantity)
{
//implement code to change the quantity of an item
String item_updated = "Quantity for Item Id: " + String.valueOf(itemID) + ", Cost: $";
//modify item_updated to display data in the following format- 'Quantity for Item Id: 123, Cost: $20.50 is changed to 25'
//print item_updated
}
public void removeItemFromCart(int itemID)
{
//implement here
}
public double calculateItemBasedDiscount()
{
double discount = 0;
//If total number of quantity ACROSS ALL Items is less than 11 , apply LOW_DISCOUNT (10% discount)
//If total number of quantity ACROSS ALL Items is more than 10 but less than 26, apply MEDIUM_DISCOUNT (25% discount)
//If total number of quantity ACROSS ALL Items is more than 26, apply HIGH_DISCOUNT (50% discount)
return discount;
}
/**
*
* @return
*/
public double getTotalCost() {
double totalFinalCost = 0;
//Compute the cost by adding cost of each item. Make sure to multiply quantity and price per unit for cost of each item.
//Find applicable discount using calculateItemBasedDiscount and apply the discount to find the final cost
return totalFinalCost;
}
}
-------------------------------------
//add package statement here
public class Item {
private int id;
private double price;
public Item(int id, double price){
this.id = id;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString(){
String item_desc = "Item Id: " + String.valueOf(id) + ", Cost: $";
//modify item_desc to contain item description in the following format- Item Id: 123, Cost: $20.50 added in ShoppingCart with Quantity 20
return item_desc;
}
}
------------------------------
//add package statement here
public class ShoppingCartTester {
public static void main(String[] args) {
//Add code here to display main menu along with all the options
//Keep on looping until the user enters 6 to exit. DO NOT EXIT otherwise
//If any number other than 1-6 is entered, display an error message "Enter input in the range 1-6"; and again ask for input
//Demo code
/*
ShoppingCart shoppingCart= new ShoppingCart();
System.out.println("Add Item Id: 1");
System.out.println("Add Item Cost per unit: 1.5");
int id = 1;
double costPerUnit = 1.5;
int quantity = 10;
Item item = new Item(id, costPerUnit);
shoppingCart.addItemToCart(item, quantity);
userInputSimulator();
*/
}
public static void userInputSimulator()
{
//Use Scanner to get input for item quantity and item cost
ShoppingCart shoppingCart = new ShoppingCart();
shoppingCart.addItemToCart(item, quanity);();
//System.out.print("Discount Code should be 0.5 : " + discountLevel);
double finalCost = order.getTotalCost();
//System.out.print("FInal cost should be : " + finalCost);
//Additional testing
//Add sensible function calls to test functionality of ALL methods in ShoppingCart.java
//Display the final cost
}
}
/* Note:
Perform error handling. Eg: donot accept values outside the range(1-6) donot accept negative values for QUANTITY or PRICE of an ITEM
*/
Explanation / Answer
Hello, I have a solution for you. Implemented everything as per the requirements. Defined following things in this answer.
1. Made appropriate modifications to the Item class to include an attribute for storing item quantity, and a method
equals() to check if two Items are same (important for ArrayList method contains() to work correctly).
2. Modified the ShoppingCart classes, completed all the incomplete methods.
3. Completed the ShoppingCartTester program, implemented userInputSimulator() method , executed the program, verified
the output.
4. Comments are included, If you have any doubts, feel free to ask, Thanks
EDIT: getting character limit exceeded error while trying to paste without losing the format, so I’m pasting as plain
text, sorry if the code indentation and format is messed up.
// Item.java
public class Item {
private int id;
private double price;
private int quantity;
public Item(int id, double price) {
this.id = id;
this.price = price;
this.quantity = 0;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String toString() {
String item_desc = String
.format("Item Id: %d, Cost: $%.2f added in ShoppingCart with quantity %d",
id, price, quantity);
// modify item_desc to contain item description in the following format-
// Item Id: 123, Cost: $20.50 added in ShoppingCart with Quantity 20
return item_desc;
}
/**
* This method checks if two Item objects are equal, this is very important
* for the ArrayList method contains() to work
*/
@Override
public boolean equals(Object o) {
if (o instanceof Item) {
Item i = (Item) o;// safe type casting
if (i.id == this.id) {
return true;
}
}
return false;
}
}
// ShoppingCart.java
import java.util.ArrayList;
public class ShoppingCart {
public static final double LOW_DISCOUNT = 0.10;
public static final double MEDIUM_DISCOUNT = 0.25;
public static final double HIGH_DISCOUNT = 0.50;
ArrayList<Item> itemArray = new ArrayList<Item>();
private String customerName;
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public ShoppingCart(String customerName) {
this.customerName = customerName;
}
public void addItemToCart(Item item, int quantity) {
if (itemArray.contains(item)) {
/**
* Already exist, updating the quantity
*/
updateItemQuantity(item.getId(), quantity);
} else {
/**
* setting the quantity and adding the item to the cart
*/
item.setQuantity(quantity);
itemArray.add(item);
//displaying details
System.out.println(item);
}
// If item already exists then update the quantity of that item by
// calling updateItemQuantity
// If a new item is added, add the item to itemArray and fetch the
// details of the item added by calling toString() in Item;
// print the fetched string here
// donot display the details here if the item is updated, that should be
// done inside updateItemQuantity()
}
public void addItemToCart(int itemId, double itemPrice, int itemQuantity) {
/**
* Defining an item object
*/
Item item = new Item(itemId, itemPrice);
/**
* Adding to the cart
*/
addItemToCart(item, itemQuantity);
// Create Object of Item
// Call addItemToCart(Item item, int quanity)
}
public void updateItemQuantity(int itemID, int newQuantity) {
/**
* updating the quantity of existing item
*/
boolean found = false;
for (int i = 0; i < itemArray.size(); i++) {
if (itemArray.get(i).getId() == itemID) {
found = true;
//updating the quantity
itemArray.get(i).setQuantity(newQuantity);
//displaying the details
String item_desc = String
.format("Quantity for Item Id: %d, Cost: $%.2f is changed to %d",
itemID, itemArray.get(i).getPrice(),
newQuantity);
System.out.println(item_desc);
break;
}
}
if (!found) {
//not found
System.out.println("Specified item not found in the Cart!");
}
}
public void removeItemFromCart(int itemID) {
/**
* Defining an Item object with the given id, so that it can be searched
* on the list using contains() method of ArrayList, which will check
* for the items with same item id only (as we have defined)
*/
Item itm = new Item(itemID, 0);
if (itemArray.contains(itm)) {
/**
* item exists, removing it
*/
itemArray.remove(itm);
System.out.println("Item with id "+itemID+" has been removed from the cart!");
}else{
/**
* Not found
*/
System.out.println("Item with id "+itemID+" is not found in the cart!");
}
}
public double calculateItemBasedDiscount() {
double discount = 0;
// If total number of quantity ACROSS ALL Items is less than 11 , apply
// LOW_DISCOUNT (10% discount)
// If total number of quantity ACROSS ALL Items is more than 10 but less
// than 26, apply MEDIUM_DISCOUNT (25% discount)
// If total number of quantity ACROSS ALL Items is more than 26, apply
// HIGH_DISCOUNT (50% discount)
int totalQuantity=0;
double totalNotDiscountedPrice=0;
/**
* Looping through the items in the cart, find the total quantity and total cost
*/
for(Item i:itemArray){
totalQuantity+=i.getQuantity();
totalNotDiscountedPrice+=i.getPrice()*i.getQuantity();
}
/**
* Finding the proper discount
*/
if(totalQuantity<=10){
discount=totalNotDiscountedPrice*LOW_DISCOUNT;
}else if(totalQuantity>10 && totalQuantity<=26){
discount=totalNotDiscountedPrice*MEDIUM_DISCOUNT;
}else{
discount=totalNotDiscountedPrice*HIGH_DISCOUNT;
}
/**
* returning the discount amount
*/
return discount;
}
/**
*
* @return the final cost after deducting all discounts
*/
public double getTotalCost() {
double totalFinalCost = 0;
/**
* Finding the total not discounted price
*/
for(Item i:itemArray){
totalFinalCost+=i.getPrice()*i.getQuantity();
}
/**
* applying the discount
*/
totalFinalCost-=calculateItemBasedDiscount();
/**
* returning the final price
*/
return totalFinalCost;
}
}
// ShoppingCartTester.java
import java.util.Scanner;
public class ShoppingCartTester {
static Scanner scanner;
static ShoppingCart cart;
public static void main(String[] args) {
/**
* Initializing the scanner
*/
scanner = new Scanner(System.in);
System.out.println("WELCOME TO SHOPPING CART APPLICATION");
System.out.println("PLEASE ENTER YOUR NAME: ");
String name = scanner.nextLine();
/**
* Initializing the cart
*/
cart = new ShoppingCart(name);
System.out.println("Welcome " + name
+ ". Your Shopping Cart is created.");
/**
* interacting with user until he chooses to quit
*/
userInputSimulator();
}
/**
* method to interact with the user and perform appropriate actions
*/
public static void userInputSimulator() {
int choice = 0;
int itemId, quantity;
double price;
/**
* loops until the choice = 6 (user wishes to quit)
*/
while (choice != 6) {
// displaying the menu
displayMenu();
try {
// getting the choice
choice = Integer.parseInt(scanner.nextLine());
/**
* performing operations based on the choice
*/
switch (choice) {
case 1:
/**
* getting inputs
*/
System.out
.println("You have selected to Add Item in Shopping Cart");
System.out.println("Please Enter Item Id:");
itemId = Integer.parseInt(scanner.nextLine());
System.out.println("Please Enter Item Price:");
price = Double.parseDouble(scanner.nextLine());
if (price < 0) {
System.out.println("ERROR: price can't be negative!");
break;
}
System.out.println("Please Enter Item Quantity:");
quantity = Integer.parseInt(scanner.nextLine());
if (quantity < 0) {
System.out
.println("ERROR: quantity can't be negative!");
break;
}
/**
* Adding to the cart
*/
cart.addItemToCart(itemId, price, quantity);
break;
case 2:
System.out
.println("You have selected to update Quantity for Item in
ShoppingCart");
System.out
.println("Please Enter Item Id for which you want to change
Quantity:");
itemId = Integer.parseInt(scanner.nextLine());
System.out.println("Please Enter new Quantity:");
quantity = Integer.parseInt(scanner.nextLine());
/**
* updating the quantity
*/
cart.updateItemQuantity(itemId, quantity);
break;
case 3:
System.out
.println("You have selected to remove an Item from ShoppingCart");
System.out
.println("Please Enter Item Id of the Item to be removed:");
itemId = Integer.parseInt(scanner.nextLine());
cart.removeItemFromCart(itemId);
break;
case 4:
System.out.printf("Total discounted amount is $%.2f ",
cart.calculateItemBasedDiscount());
break;
case 5:
System.out.printf(
"Final cost after deducting discounts is $%.2f ",
cart.getTotalCost());
break;
case 6:
System.out.println("Are you sure you want to exit? (y/n)");
if (scanner.nextLine().equalsIgnoreCase("y")) {
System.out.println("Good bye, have a nice day!");
/**
* end of the loop, will not execute next time
*/
} else {
/**
* setting choice to 0, so that it will execute again
*/
choice = 0;
}
break;
default:
System.out.println("Invalid choice, try again!");
break;
}
} catch (Exception e) {
System.out.println("Invalid input!");
}
}
}
/**
* method to display the menu
*/
static void displayMenu() {
System.out.println("Select one of the following options:");
System.out.println("1. Add Item in ShoppingCart");
System.out.println("2. Update Quantity for Item in ShoppingCart");
System.out.println("3. Remove Item from Shopping Cart");
System.out.println("4. Calculate Item Based Discount");
System.out.println("5. Get total cost");
System.out.println("6. Exit");
}
}
/*OUTPUT*/
WELCOME TO SHOPPING CART APPLICATION
PLEASE ENTER YOUR NAME:
Alice
Welcome Alice. Your Shopping Cart is created.
Select one of the following options:
1. Add Item in ShoppingCart
2. Update Quantity for Item in ShoppingCart
3. Remove Item from Shopping Cart
4. Calculate Item Based Discount
5. Get total cost
6. Exit
1
You have selected to Add Item in Shopping Cart
Please Enter Item Id:
1234
Please Enter Item Price:
120
Please Enter Item Quantity:
6
Item Id: 1234, Cost: $120.00 added in ShoppingCart with quantity 6
Select one of the following options:
1. Add Item in ShoppingCart
2. Update Quantity for Item in ShoppingCart
3. Remove Item from Shopping Cart
4. Calculate Item Based Discount
5. Get total cost
6. Exit
1
You have selected to Add Item in Shopping Cart
Please Enter Item Id:
2233
Please Enter Item Price:
200
Please Enter Item Quantity:
2
Item Id: 2233, Cost: $200.00 added in ShoppingCart with quantity 2
Select one of the following options:
1. Add Item in ShoppingCart
2. Update Quantity for Item in ShoppingCart
3. Remove Item from Shopping Cart
4. Calculate Item Based Discount
5. Get total cost
6. Exit
2
You have selected to update Quantity for Item in ShoppingCart
Please Enter Item Id for which you want to change Quantity:
2233
Please Enter new Quantity:
22
Quantity for Item Id: 2233, Cost: $200.00 is changed to 22
Select one of the following options:
1. Add Item in ShoppingCart
2. Update Quantity for Item in ShoppingCart
3. Remove Item from Shopping Cart
4. Calculate Item Based Discount
5. Get total cost
6. Exit
3
You have selected to remove an Item from ShoppingCart
Please Enter Item Id of the Item to be removed:
1234
Item with id 1234 has been removed from the cart!
Select one of the following options:
1. Add Item in ShoppingCart
2. Update Quantity for Item in ShoppingCart
3. Remove Item from Shopping Cart
4. Calculate Item Based Discount
5. Get total cost
6. Exit
4
Total discounted amount is $1100.00
Select one of the following options:
1. Add Item in ShoppingCart
2. Update Quantity for Item in ShoppingCart
3. Remove Item from Shopping Cart
4. Calculate Item Based Discount
5. Get total cost
6. Exit
5
Final cost after deducting discounts is $3300.00
Select one of the following options:
1. Add Item in ShoppingCart
2. Update Quantity for Item in ShoppingCart
3. Remove Item from Shopping Cart
4. Calculate Item Based Discount
5. Get total cost
6. Exit
6
Are you sure you want to exit? (y/n)
y
Good bye, have a nice day!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.