Question

DESCRIPTION You have to design an e-commerce shopping cart. These require classes Item, Electronics, Food, Dress,...

DESCRIPTION You have to design an e-commerce shopping cart. These require classes Item, Electronics, Food, Dress, Cart and Main.

ITEM CLASS Your Item class should contain:

Attributes (protected)

String name - name of the Item

double price - price of the item

Methods (public)

void setName(String n) - sets the name of Item

void setPrice(double p) - sets the price of Item

String getName() - retrieves name

double getPrice() - retrieves price

String formattedOutput() returns a string containing detail of the Item as "Name,price" (without the quotes, no space only comma separating the values, for example: Apple,1.00

Constructors

Item(String n, double p) - constructor, sets name=n & price=p.

Item() - default constructor, sets name="" & price=0

ELECTRONICS CLASS

Your Electronics class inherits from Item. It should have following:

Attributes (private)

String model

int year

Methods (public)

void setModel(String m) - sets the model of Electronics.

void setYear(int year) - sets the manufacturing year of Electronics. If year<0, it is considered an invalid input and ignored (no update)

String getModel() - retrieves model.

int getYear() - retrieves manufacturing year.

String formattedOutput() overrides method from Item class and returns a string containing detail of the Electronic as "Name,price,model,makeYear" (without the quotes, no space only comma separating the values, for example: Probook,HP,2018,590.00

Constructors

Electronics(String n, double p, String md, int my) - If year<0, set it to 0.

Electronics() - default constructor, sets String attributes to "" and int/double to 0/0.00.

FOOD CLASS

Your Food class inherits from Item. It should have following:

Attributes (private)

double weight

String weightUnit

Methods (public)

void setWeightUnit(String wu) - sets the weightUnit of Food.

void setWeight(double wt) - sets the weight of Food. If w<0, no update is required.

String getWeightUnit() - retrieves weightUnit.

double getWeight() - retrieves weight.

String formattedOutput() overrides method from Item class and returns a string containing detail of the Food as "Name,prince,weight,weightUnit" (without the quotes, no space only comma separating the values, for example: Greens,1,lb,2.49

Constructors

Food(String n, double p, double w, String wu) - If w<0, set it to 0.

Food() - default constructor, sets String attributes to "" and int/double to 0/0.00.

DRESS CLASS

Your Dress class inherits from Item. It should have following:

Attributes (private)

String size

String fabric

Methods (public)

Constructor with parameters.

Additional set/get functions for new attributes.

String formattedOutput() overrides method from Item class and returns a string containing detail of the Food as "Name,price,size,fabric" (without the quotes, no space only comma separating the values, for example: Shirt,Small,cotton,9.49

Constructors

Dress(String n, double p, String s, String f)

Dress() - default constructor, sets String attributes to "" and int/double to 0/0.00.

CART CLASS

Your Cart class should contain:

Attributes (private)

Item items[] - Items in the cart. Size of this array is initialized in constructor.

int itemQuantities[] – quantity of each item in the cart. Example: A cart has 2 apples and 1 computer. item[0] has Apple with quantity[0] =2, Item[1] has Computer with quantity[1] = 1 i.e. quantity[i] is the quantity of item[i]

int itemCount – number of items (types, not quantities) at any given state. For above example if you have 2 apples and 1 Electronics in the cart, your itemCount should be 2.

double totalPrice - price of all the items in the cart

int totalQuantity - quantity of all the items in the cart. For above example, total quantity is 3.

Constructors

Cart() - sets default value cartSize to 10 and creates arrays items & itemQuantities arrays having size 10, initializes other int/double type attributes to 0/0.00.

Cart(int cartSize) - sets cartSize and creates arrays items & itemQuantities arrays having size cartSize, initializes other int/double type attributes to 0/0.00.. If cartSize is less than or equal to zero, set it to default size 10.

Methods - all methods are public (unless mentioned)

int getItemCount() - retrieves itemCount

double getTotalPrice() - retrieves totalPrice

int getTotalQuantity() - retrieves totalQuatnity

int getCartSize() - retrieves cartSize

void setCartSize(int newCartSize) - sets cartSize. It always works if newCartSize greater than current cartSize. If the newCartSize is less than current cartSize, resize only if itemCount is less than newCartSize, otherwise leave unchanged. If newCartSize is less than or equal to zero, no update is done.

void add (Item item, int addQuantity) - to add items to the cart. Make sure you can only add items if there is enough room in the cart (the quantity of each item does not matter). If an item is added (you can use searchItem method here) that is already in the cart, increase the quantity, but do not duplicate the item. If addQuantity is less than or equal to zero, no update is required.

void remove (Item item, int removeQuantity) - to remove removeQuantity number of items from the cart (if the removeQuantity is greater than quantity of items in the cart, it removes all of them). For example, you have 7 apples in the cart and removeItem(“Apples”,15) is called, then you remove all 7 of them (including the item from the cart), but if removeItem(“Apples”,5) is called, you remove 5 of them and 2 apples remain in the cart. Note that, you can only remove item if it is present in the cart (you can use searchItem method). If removeQuantity is less than or equal to zero, no update is required.

private int search (Item item) – returns index of the item in the array if found, or -1 if item is not found in the cart. Compare name of the item only. This is a helper function you can use in addItem or removeItem method.

String formattedOutput() - Calls the formattedOutput() function of all items in the cart, followed by the quantity of each item type in cart, and its total price (the price should reflect the quantity). Finally, formattedOutput() should include the total number of items in the cart and the total price of all items in the cart.

MAIN CLASS

This file already has a template with empty main() method. Your Main class in Zybook should look like:

public class Main {
    public static void main(String[] args) {       

    }
}

BONUS (20 points)

Modify int searchItem(Item item) method in Cart class, to compare items considering all of their attributes. You have to use instance of operator for this. You are not allowed to use any new method(s) for this task. For example, if the name matches for Electronics class object, you need to check price, model and year. However, if it’s a Dress class object, you need to check if price, size and fabric matches. For example: without implementing bonus, following two items would be taken as same: Probook,HP,2008,190.00 and Probook,HP,2019,690.00, but would be different with the bonus version of searchItem.

TESTING & SUBMISSION

You can either work in Zybook editor or your favorite IDE. But if you use IDE, you have to copy your code to Zybook editor.

If you use your own IDE, you can use Test.java (uploaded in Blackboard) to test your code. Test.java contains 20 sample test cases and 2 bonus test cases. Your code will be tested with similar test cases. However, grading test cases will be different, for example: all the values will be changed (unless default values mentioned in the description). So don't hard code any part of your code to pass these test cases only.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi,

Code:

import jdk.nashorn.internal.ir.SetSplitState;

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

   public Item() {
       this.name = "";
       this.price = 0;
   }

   public void setName(String n) {
       name = n;
   }

   public void setPrice(double p) {
       price = p;
   }

   public String getName() {
       return name;
   }

   double getPrice() {
       return price;
   }

   public String formattedOutput() {// example: Apple,1.

       return getName() + ", " + getPrice() + "\n";
   }

}

class Electronics extends Item {

   private String model;
   private int year;

   public void setModel(String m) {
       this.model = m;
   }

   public void setYear(int year) {// If year<0, it is considered an invalid input and ignored (no update)

       if (year > 0)
           this.year = year;

   }

   public String getModel() {
       return model;
   }

   public int getYear() {
       return year;
   }

   public String formattedOutput() {// overrides method from Item class and returns a string containing detail of
                                       // the
                                       // Electronic as "Name,price,model,makeYear" (without the quotes, no space only
                                       // comma separating the values, for example: Probook,HP,2018,590.00
       return getName() + ", " + getModel() + ", " + getYear() + ", " + getPrice() + "\n";
   }

   public Electronics(String n, double p, String md, int my) {// If year<0, set it to 0.
       if (my < 0)
           this.year = 0;
       else
           this.year = my;
       setName(n);
       model = md;
   }

   public Electronics() {// default constructor, sets String attributes to "" and int/double to 0/0.00.
       setName("");
       model = "";
       year = 0;
       setPrice(0.00);
   }
}

class Food extends Item {
   private double weight;
   private String weightUnit;

   public void setWeightUnit(String wu) {// - sets the weightUnit of Food.
       this.weightUnit = wu;
   }

   public void setWeight(double wt) { // sets the weight of Food. If w<0, no update is required.
       this.weight = wt;
   }

   public String getWeightUnit() {// retrieves weightUnit.
       return weightUnit;
   }

   public double getWeight() {// retrieves weight.
       return weight;
   }

   public String formattedOutput() {// overrides method from Item class and returns a string containing detail of
                                       // the
                                       // Food as "Name,prince,weight,weightUnit" (without the quotes, no space only
                                       // comma
                                       // separating the values, for example: Greens,1,lb,2.49
       return getName() + ", " + getWeight() + ", " + getWeightUnit() + ", " + getPrice() + "\n";
   }

   public Food(String n, double p, double w, String wu) {// - If w<0, set it to 0.

       if (w < 0)
           weight = 0;
       else
           weight = w;
       weightUnit = wu;
       setName(n);
       setPrice(p);

   }

   public Food() { // sets String attributes to "" and int/double to 0/0.00.
       setName("");
       setPrice(0.00);
       setWeightUnit("");
       setWeight(0.00);
   }
}

class Dress extends Item {
   private String size;
   private String fabric;

   public void setSize(String s) {
       this.size = s;
   }

   public String getSize() {
       return size;
   }

   public void setFabric(String f) {
       this.fabric = f;
   }

   public String getFabric() {
       return fabric;
   }

   public String formattedOutput() {// overrides method from Item class and returns a string containing
                                       // detail of the Food as "Name,price,size,fabric" (without the quotes,
                                       // no space only comma separating the values, for example:
                                       // Shirt,Small,cotton,9.49
       return getName() + ", " + getSize() + ", " + getFabric() + ", " + getPrice();
   }

   public Dress(String n, double p, String s, String f) {
       setName(n);
       setPrice(p);
       setSize(s);
       setFabric(f);
   }

   public Dress() {// - default constructor, sets String attributes to "" and int/double to 0/0.00.
       setName("");
       setPrice(0.00);
       setSize("");
       setFabric("");
   }
}

class Cart {

   private Item items[]; // - Items in the cart. Size of this array is initialized in constructor.
   private int itemQuantities[]; // – quantity of each item in the cart. Example: A cart has 2 apples and 1
                                   // computer. item[0] has Apple with quantity[0] =2, Item[1] has Computer with
                                   // quantity[1] = 1 i.e. quantity[i] is the quantity of item[i]

   private int itemCount; // – number of items (types, not quantities) at any given state.
                           // For above example if you have 2 apples and 1 Electronics in the cart, your
                           // itemCount should be

   private double totalPrice;// - price of all the items in the cart

   private int totalQuantity; // - quantity of all the items in the cart. For above example, total quantity is
                               // 3.
   private int cartSize;

   public Cart() {
       cartSize = 10;
       itemCount = 0;
       totalPrice = 0.00;
       totalQuantity = 0;
   }

   public Cart(int cartSize) {
       if (cartSize <= 0) {
           this.cartSize = 10;
       } else {
           this.cartSize = cartSize;
       }
       itemCount = 0;
       totalPrice = 0.00;
       totalQuantity = 0;

   }

   public int getItemCount() { // - retrieves itemCount
       return itemCount;
   }

   public double getTotalPrice() { // - retrieves totalPrice
       return totalPrice;
   }

   public int getTotalQuantity() { // - retrieves totalQuatnity
       return totalQuantity;
   }

   int getCartSize() {// - retrieves cartSize
       return cartSize;
   }

   public void setCartSize(int newCartSize) {

       if (newCartSize > cartSize) {
           this.cartSize = newCartSize;

       } else if (newCartSize < cartSize && itemCount < newCartSize) {
           this.cartSize = newCartSize;
       }
   }

   public void add(Item item, int addQuantity) {
       int i;
       if(items == null) {
           items = new Item[cartSize];
           itemQuantities= new int[cartSize];
           i=0;
       }else
           i = items.length;
       if ( i==0 || i < getCartSize()) {
           items[i] = new Item();
           items[i]=item;
           itemQuantities[i] = addQuantity;
       }
      
   }

   public void remove(Item item, int removeQuantity) {

       for (int i = 0; i < cartSize; i++) {
           if (items[i] == item) {
               if (removeQuantity > itemQuantities[i]) {
                   items[i] = null;
                   itemQuantities[i] = 0;
               } else
                   itemQuantities[i] = itemQuantities[i] - removeQuantity;
           }
       }
   }

   private int search(Item item) {
       for (int i = 0; i < cartSize; i++) {
           if (items[i].getName().equals(item.getName()))
               return i;
       }
       return -1;
   }

   public void calculateTotalPrice() {
       double t = 0;
       for (int i = 0; i < cartSize; i++) {
           t += items[i].getPrice();
       }

       totalPrice = t;
   }

   public String formattedOutput() {

       String output = "";
       for (int i = 0; i < cartSize; i++) {
           if(items[i] != null)
               output += items[i].getName() + "," + itemQuantities[i] + ", " + itemQuantities[i] * items[i].getPrice()
                   + "\n";
       }

       //output += getItemCount() + ", " + getTotalPrice() + "\n";

       return output;
   }
}

public class Main {
   public static void main(String[] args) {

       try {
           int size = 2;
           Item it1 = new Item("Coke", 50.00);
           it1.formattedOutput();
          
           System.out.print(it1.formattedOutput());

           Item it2 = new Item("Shirt", 500.00);
          
           System.out.print(it2.formattedOutput());


           Cart c = new Cart(2);

           c.add(it1, 2);
           c.add(it2, 4);

       } catch (Exception e) {
           // TODO: handle exception
           e.printStackTrace();
       }

   }
}

Screenshot:lss rase iactroniterseas rod.class iten.ctass uitn-clas katn. jevw ramesh@raneshk: /Music/Java_prgs/carts ass Food.cla ramesh@raneshk:/Music/Java_prgs/carts java Main Coke, 50.0 Shirt, 500.0 ramesh@rameshk:-/Music/Java_prgs/carts

Add a comment
Know the answer?
Add Answer to:
DESCRIPTION You have to design an e-commerce shopping cart. These require classes Item, Electronics, Food, Dress,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 4.18 Ch 7 Program: Online shopping cart (continued) (C++) This program extends the earlier "Online shopping...

    4.18 Ch 7 Program: Online shopping cart (continued) (C++) This program extends the earlier "Online shopping cart" program. (solution from previous lab assignment is provided in Canvas). (1) Extend the ItemToPurchase class per the following specifications: Parameterized constructor to assign item name, item description, item price, and item quantity (default values of 0). (1 pt) Public member functions SetDescription() mutator & GetDescription() accessor (2 pts) PrintItemCost() - Outputs the item name followed by the quantity, price, and subtotal PrintItemDescription() -...

  • Warm up: Online shopping cart (Part 1)

    8.6 LAB*: Warm up: Online shopping cart (Part 1)(1) Create two files to submit:ItemToPurchase.java - Class definitionShoppingCartPrinter.java - Contains main() methodBuild the ItemToPurchase class with the following specifications:Private fieldsString itemName - Initialized in default constructor to "none"int itemPrice - Initialized in default constructor to 0int itemQuantity - Initialized in default constructor to 0Default constructorPublic member methods (mutators & accessors)setName() & getName() (2 pts)setPrice() & getPrice() (2 pts)setQuantity() & getQuantity() (2 pts)(2) In main(), prompt the user for two items and create...

  • This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program).

    Ch 7 Program: Online shopping cart (continued) (Java)This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program).(1) Extend the ItemToPurchase class per the following specifications:Private fieldsstring itemDescription - Initialized in default constructor to "none"Parameterized constructor to assign item name, item description, item price, and item quantity (default values of 0). (1 pt)Public member methodssetDescription() mutator & getDescription() accessor (2 pts)printItemCost() - Outputs the item name followed by the quantity, price, and subtotalprintItemDescription() - Outputs the...

  • JAVA i need write java program Object Classes: designing Shopping Cart 1.Shopping Cart , build a...

    JAVA i need write java program Object Classes: designing Shopping Cart 1.Shopping Cart , build a checkout system for a shop which sells items (i.e., products say Bread, Milk, and Bananas). A shopping cart that can have multiples. Costs of the products are : Bread - $1, Milk - $0.60 and Banana - $0.40. A system should displays the order total. 2.The heart of a shopping cart can be represented in three classes: a cart class an order class, and...

  • I need help with this assignment, can someone HELP ? This is the assignment: Online shopping...

    I need help with this assignment, can someone HELP ? This is the assignment: Online shopping cart (continued) (C++) This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program). (1) Extend the ItemToPurchase class per the following specifications: Parameterized constructor to assign item name, item description, item price, and item quantity (default values of 0). (1 pt) Public member functions SetDescription() mutator & GetDescription() accessor (2 pts) PrintItemCost() - Outputs the item name followed by...

  • 11.11 LAB: Warm up: Online shopping cart (1) Build the ItemToPurchase class with the following specifications:...

    11.11 LAB: Warm up: Online shopping cart (1) Build the ItemToPurchase class with the following specifications: Attributes (6 pts) item_name (string) item_price (float) item_quantity (int) Default constructor (2 pt) Initializes item's name = "none", item's price = 0, item's quantity = 0 Method print_item_cost() Ex. of print_item_cost() output: Bottled Water 10 @ $1 = $10 (2) In the main section of your code, prompt the user for two items and create two objects of the ItemToPurchase class. (4 pts) Ex:...

  • 11.12 LAB*: Program: Online shopping cart (continued) This program extends the earlier "Online shopping cart" pr...

    11.12 LAB*: Program: Online shopping cart (continued)This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program).(1) Extend the ItemToPurchase class to contain a new attribute. (2 pts)item_description (string) - Set to "none" in default constructorImplement the following method for the ItemToPurchase class.print_item_description() - Prints item_description attribute for an ItemToPurchase object. Has an ItemToPurchase parameter.Ex. of print_item_description() output:Bottled Water: Deer Park, 12 oz.(2) Build the ShoppingCart class with the following data attributes and related methods. Note: Some can be method stubs...

  • c++ Error after oveloading, please help? LAB #8- CLASSES REVISITED &&    Lab #8.5 …      Jayasinghe...

    c++ Error after oveloading, please help? LAB #8- CLASSES REVISITED &&    Lab #8.5 …      Jayasinghe De Silva Design and Implement a Program that will allow all aspects of the Class BookType to work properly as defined below: class bookType { public:    void setBookTitle(string s);            //sets the bookTitle to s    void setBookISBN(string ISBN);            //sets the private member bookISBN to the parameter    void setBookPrice(double cost);            //sets the private member bookPrice to cost    void setCopiesInStock(int noOfCopies);            //sets the private member copiesInStock to...

  • 8.7 LAB*: Program: Online shopping cart (Part 2)

    8.7 LAB*: Program: Online shopping cart (Part 2)Note: Creating multiple Scanner objects for the same input stream yields unexpected behavior. Thus, good practice is to use a single Scanner object for reading input from System.in. That Scanner object can be passed as an argument to any methods that read input.This program extends the earlier "Online shopping cart" program. (Consider first saving your earlier program).(1) Extend the ItemToPurchase class per the following specifications:Private fieldsstring itemDescription - Initialized in default constructor to "none"Parameterized...

  • Zybooks 11.12 LAB*: Program: Online shopping cart (continued) Python 3 is the code needed and this...

    Zybooks 11.12 LAB*: Program: Online shopping cart (continued) Python 3 is the code needed and this is in Zybooks Existing Code # Type code for classes here class ItemToPurchase: def __init__(self, item_name="none", item_price=0, item_quantity=0): self.item_name = item_name self.item_price = item_price self.item_quantity = item_quantity # def __mul__(self): # print_item_cost = (self.item_quantity * self.item_price) # return '{} {} @ ${} = ${}' .format(self_item_name, self.item_quantity, self.item_price, print_item_cost) def print_item_cost(self): self.print_cost = (self.item_quantity * self.item_price) print(('{} {} @ ${} = ${}') .format(self.item_name, self.item_quantity, self.item_price,...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT