Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA: Write classes to model a shopping list. Make an Item class that represents

ID: 3769374 • Letter: J

Question

JAVA: Write classes to model a shopping list. Make an Item class that represents a grocery item's name and price, such as tissues for $3. Also implement an ItemOrder class that represents a shopper's desire to purchase a given item in a given quantity, such as five boxes of tissues. You should also implement a discounting function per ItemOrder, so that a discount of 0.25 means, for example, 25% off of that item order. Lastly, implement a ShoppingCart class that stores ItemOrders in an ArrayList and allows item orders to be added to, removed from, or searched for in the cart. The cart should be able to report the total price of all item orders it currently carries.

Explanation / Answer

// Item.java

public class Item{
   String name;
   double price;
   Item(String n, double p){
       name = n;
       price = p;
   }
}

// ItemOrder.java

public class ItemOrder{
   Item item;
   int quantity;
   ItemOrder(Item i, int q){
       item = i;
       quantity = q;
   }
   double discount(double percent){
       return item.price * quantity * percent / 100.0;
   }
}

// ShoppingCart.java

import java.util.ArrayList;
import java.util.Scanner;

public class ShoppingCart{
   ArrayList<ItemOrder> cart;
   ShoppingCart(){
       cart = new ArrayList<ItemOrder>();
   }
   void add(){
       Scanner in = new Scanner(System.in);
       System.out.print("Enter the name of the item to be added: ");
       String name = in.next();
       System.out.print("Enter the price of the item to be added: ");
       int price = in.nextInt();
      
       Item i = new Item(name, price);
       System.out.print("Enter the quantity of the item to be added: ");
       int qty = in.nextInt();
       cart.add(new ItemOrder(i, qty));
   }
   void remove(){
       Scanner in = new Scanner(System.in);
       System.out.print("Enter the name of the item to be removed: ");
       String name = in.next();
       for(int i = 0; i < cart.size(); i++){
           if(cart.get(i).item.name.equalsIgnoreCase(name)){
               cart.remove(i);
               break;
           }
       }
   }
   void search(){
       Scanner in = new Scanner(System.in);
       System.out.print("Enter the name of the item to search: ");
       String name = in.next();
       for(int i = 0; i < cart.size(); i++){
           if(cart.get(i).item.name.equalsIgnoreCase(name)){
               System.out.println("Item name: " + name + ", price: " + cart.get(i).item.price + ", quantity: " + cart.get(i).quantity);
               break;
           }
       }
   }
   double totalPrice(){
       double sum = 0;
       for(int i = 0; i < cart.size(); i++){
           sum += cart.get(i).item.price * cart.get(i).quantity - cart.get(i).discount(25);
       }
       return sum;
   }
}