Question

In: Computer Science

Demonstrate the following: Usage of Eclipse Variable Assignment Looping (for, while etc) ArrayList (using object) Object...

Demonstrate the following:

  1. Usage of Eclipse
  2. Variable Assignment
  3. Looping (for, while etc)
  4. ArrayList (using object)
  5. Object based programming
  6. User Interaction with multiple options
  7. Implementing Methods in relevant classes

Instructions

  • Start with below java files:
  • Item.java
    • Pages

      //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;

      }

      }

  • ShoppingCart.java
    • /**

      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<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){

      //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;

      }

      }

  • ShoppingCartTester.java
    • //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:

      Meticulously read the instructions explaining how marks will be awarded for this

      assignment.

      Perform error handling. Eg: donot accept values outside the range(1-6) donot accept

      negative values for QUANTITY or PRICE of an ITEM

      */

  • 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!

Solutions

Expert Solution

// Item.java

public class Item {

   private int id;

   private double price;

   private int itemQuantity;

   public Item(int id, double price, int qty) {

       this.id = id;

       this.price = price;
       this.itemQuantity = qty;

   }

   public int getItemQuantity() {
       return itemQuantity;
   }

   public void setItemQuantity(int itemQuantity) {
       this.itemQuantity = itemQuantity;
   }

   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: $"
               + price + " added in ShoppingCart with Quantity "
               + itemQuantity;

       // 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;

   }
}

_________________________

// ShoppingCart.java

/**

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<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) {

       // implement here
       setCustomerName(customerName);

   }

   public void addItemToCart(Item item, int quanity) {
       int flag = 0;
       // 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

       // do not display the details here if the item is updated, that should
       // be done inside updateItemQuantity()
       for (int i = 0; i < itemArray.size(); i++) {
           if (itemArray.get(i).getId() == item.getId()) {
               flag = 1;
               break;
           }
       }
       if (flag == 1) {
           updateItemQuantity(item.getId(), quanity);
       } else {
           addItemToCart(item.getId(), item.getPrice(), item.getItemQuantity());
           System.out.println(item);
       }
   }

   public void addItemToCart(int itemId, double itemPrice, int itemQuantity) {

       // Create Object of Item
       Item i = new Item(itemId, itemPrice, itemQuantity);
       // Call addItemToCart(Item item, int quanity)

   }

   public void updateItemQuantity(int itemID, int newQuantity)

   {

       int indx = 0;
       // implement code to change the quantity of an item
       for (int i = 0; i < itemArray.size(); i++) {
           if (itemArray.get(i).getId() == itemID) {
               indx = i;
               break;
           }
       }

       String item_updated = "Quantity for Item Id: "
               + String.valueOf(itemArray.get(indx).getId())

               + ", Cost: $" + itemArray.get(indx).getPrice();

       itemArray.get(indx).setItemQuantity(newQuantity);

       // modify item_updated to display data in the following format-

       item_updated += " is changed to " + itemArray.get(indx).getPrice();

       // print item_updated
       System.out.println(item_updated);

   }

   public void removeItemFromCart(int itemID) {
       int indx = 0;
       // implement code to change the quantity of an item
       for (int i = 0; i < itemArray.size(); i++) {
           if (itemArray.get(i).getId() == itemID) {
               indx = i;
               break;
           }
       }
       itemArray.remove(indx);

   }

   public double calculateItemBasedDiscount()

   {

       double discount = 0;
       int totQty = 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)
       for (int i = 0; i < itemArray.size(); i++) {
           totQty += itemArray.get(i).getItemQuantity();
       }

       if (totQty < 11) {
           discount = 10;
       } else if (totQty > 10 && totQty <= 26) {
           discount = 26;
       } else if (totQty > 26) {
           discount = 50;
       }
       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.
       for (int i = 0; i < itemArray.size(); i++) {
           totalFinalCost += itemArray.get(i).getPrice()
                   * itemArray.get(i).getItemQuantity();
       }
       // Find applicable discount using calculateItemBasedDiscount and apply
       // the discount to find the final cost
       totalFinalCost = totalFinalCost + (calculateItemBasedDiscount() / 100)
               * totalFinalCost;

       return totalFinalCost;

   }

}

___________________________

// ShoppingCartTester.java

import java.util.Scanner;

public class ShoppingCartTester {

   public static void main(String[] args) {

       String customerName;
       /*
       * Creating an Scanner class object which is used to get the inputs
       * entered by the user
       */
       Scanner sc = new Scanner(System.in);

       // Getting the input entered by the user
       System.out.println("WELCOME TO SHOPPING CART APPLICATION.");
       System.out.print("PLEASE ENTER YOUR NAME:");
       customerName = sc.nextLine();
       ShoppingCart shopcart = new ShoppingCart(customerName);
       System.out.println("Welcome " + shopcart.getCustomerName()
               + ". Your Shopping Cart is created.");
       // 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
       char yesorno;
while(true)
{
   while (true) {
            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");

            int choice = sc.nextInt();
            switch (choice) {
            case 1: {
                int id,qty;
                double price;
                System.out.println("You have selected to Add Item in Shopping Cart");
                System.out.print("Please Enter Item Id:");
                id=sc.nextInt();
                System.out.print("Please Enter Item Price:");
                price=sc.nextDouble();
                System.out.print("Please Enter Item Quantity:");
                qty=sc.nextInt();
               
                shopcart.addItemToCart(id,price,qty);
                continue;
            }
            case 2: {
                System.out.println("You have selected to update Quantity for Item in ShoppingCart");
                System.out.print("Please Enter Item Id for which you want to change Quantity:");
int id=sc.nextInt();
System.out.println("Please Enter new Quantity:");
int qty=sc.nextInt();
shopcart.updateItemQuantity(id,qty);

                continue;
            }
            case 3: {
                System.out.println("You have selected to Remove Item in ShoppingCart");
                System.out.print("Please Enter Item Id for which you want to remove:");
int id=sc.nextInt();
shopcart.removeItemFromCart(id);

                continue;
            }
            case 4: {
                System.out.println("You have selected to Display ItemBasedDiscount in ShoppingCart");
                System.out.print("Discount :%"+shopcart.calculateItemBasedDiscount());
  
                continue;
            }
            case 5: {
               
        System.out.print("Total Cost :$"+shopcart.getTotalCost());
  
                continue;
            }
            case 6: {
                break;
            }
            default: {
                System.out.println("** Invalid Choice **");
                continue;
            }

            }
            break;
        }

     
   System.out.print("Are you sure you want to Exit(y/n)?");
   yesorno=sc.next(".").charAt(0);
   if(yesorno=='y' || yesorno=='Y')
   {
       break;
   }

}
System.out.println("Good Bye Have a Nice Day!");
      
   }

}

________________________________Thank You


Related Solutions

PLZ USE ECLIPSE JAVA and show output with explanation The object of this assignment is to...
PLZ USE ECLIPSE JAVA and show output with explanation The object of this assignment is to construct a mini-banking system that helps us manage banking data. Notice that you can copy and paste your code from previous assignments. This assignment asks you to allow read from/write to file, as well as search and sorting algorithm. The object of this assignment is to construct a mini-banking system that helps us manage banking data. This assignment asks you to allow read from/write...
This programming assignment is intended to demonstrate your knowledge of the following:  Writing a while...
This programming assignment is intended to demonstrate your knowledge of the following:  Writing a while loop  Write methods and calling methods Text Processing There are times when a program has to search for and replace certain characters in a string with other characters. This program will look for an individual character, called the key character, inside a target string. It will then perform various functions such as replacing the key character with a dollar-sign ($) wherever it occurs...
Struct PERSON Assignment Outcomes: Demonstrate the ability to create structs using typedef Demonstrate the ability to...
Struct PERSON Assignment Outcomes: Demonstrate the ability to create structs using typedef Demonstrate the ability to create an array of structs Program Specifications: DESIGN and IMPLEMENT a program that will CREATE and use three different variables of type PERSON. Create a struct using the typedef command for a DATE. Create a struct for a PERSON with the following fields. name [this will be a string] birthdate [this will be a DATE] gender [this will be a char] annualIncome [this will...
Struct PERSON Assignment Outcomes: Demonstrate the ability to create structs using typedef Demonstrate the ability to...
Struct PERSON Assignment Outcomes: Demonstrate the ability to create structs using typedef Demonstrate the ability to create an array of structs Program Specifications: DESIGN and IMPLEMENT a program that will CREATE and use three different variables of type PERSON. Create a struct using the typedef command for a DATE. Create a struct for a PERSON with the following fields. name [this will be a string] birthdate [this will be a DATE] gender [this will be a char] annualIncome [this will...
Struct PERSON Assignment Outcomes: Demonstrate the ability to create structs using typedef Demonstrate the ability to...
Struct PERSON Assignment Outcomes: Demonstrate the ability to create structs using typedef Demonstrate the ability to create an array of structs Program Specifications: DESIGN and IMPLEMENT a program that will CREATE and use three different variables of type PERSON. Create a struct using the typedef command for a DATE. Create a struct for a PERSON with the following fields. name [this will be a string] birthdate [this will be a DATE] gender [this will be a char] annualIncome [this will...
The objective of this homework assignment is to demonstrate proficiency with reading files, and using string...
The objective of this homework assignment is to demonstrate proficiency with reading files, and using string methods to slice strings, working with dictionaries and using-step wise development to complete your program. Python is an excellent tool for reading text files and parsing (i.e. filtering) the data. Your assignment is to write a Python program in four steps that reads a Linux authentication log file, identifies the user names used in failed password attempts and counts the times each user name...
Using an ArrayList, create a program which does the following: If the user enters quit, the...
Using an ArrayList, create a program which does the following: If the user enters quit, the program ends. If the user enters add followed by a string, program adds the string only to your ArrayList. If the user enters print, the program prints out the ArrayList contents. If the user enters size, the program prints out size of ArrayList, If the user enters remove followed by string, it removes all strings. interface example: **** Welcome to my List Program ****...
In this assignment, you will practice solving a problem using object-oriented programming and specifically, you will...
In this assignment, you will practice solving a problem using object-oriented programming and specifically, you will use the concept of object aggregation (i.e., has-a relationship between objects). You will implement a Java application, called MovieApplication that could be used in the movie industry. You are asked to implement three classes: Movie, Distributor, and MovieDriver. Each of these classes is described below. The Movie class represents a movie and has the following attributes: name (of type String), directorsName (of type String),...
In Java, Using ArrayList and HashSet data structures, as well as their methods, obtain following from...
In Java, Using ArrayList and HashSet data structures, as well as their methods, obtain following from some input text file: Total number of characters used,without counting spaces and punctuation, total number of words used; Number of words, counting each word only once; Total number of punctuation characters;Number of words that are of size six or more;Number of words that are used only once
Using Eclipse (Pyramid) Print out the following pyramid using nested loop. 1 12 123 1234 12345...
Using Eclipse (Pyramid) Print out the following pyramid using nested loop. 1 12 123 1234 12345 1) the source code (.java file), and 2) the screenshot of running results of each question.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT