Question

In: Computer Science

Can you please rewrite this Java code so it can be better understood. import java.util.HashMap; import...

Can you please rewrite this Java code so it can be better understood.

import java.util.HashMap;
import java.util.Scanner;
import java.util.Map.Entry;

public class Shopping_cart {
  
   static Scanner s= new Scanner (System.in);
  
//   declare hashmap in which key is dates as per mentioned and Values class as value which consists all the record of cases
   static HashMap<String,Item> map= new HashMap<>();

   public static void main(String[] args) {
       // TODO Auto-generated method stub
       getupdates();
   }
  
   static void getupdates() {
      
       System.out.println("Welcome to Shopping Cart. Enter:");
       System.out.println("1 : Add an Item ");
       System.out.println("2 : Add multiples Quantities of Given Item ");
       System.out.println("3 : Remove an unspecified Item ");
       System.out.println("4 : CheckOut");
       System.out.println("5 : Checkbudget");
       System.out.print("Choice: ");
       int selection= s.nextInt();
      
      
       switch(selection) {
       case 1:
          add_new_item();
          getupdates();
            
          case 2:
              Add_multiples_items();
              getupdates();
                
          case 3:
              remove_unspecified_data();
              getupdates();
                
          case 4:
                  checkout();
                  getupdates();
                 
          case 5:
                
              checkbudget();
              getupdates();
                    
          case 6:
              System.out.println("Stay Safe");
              break;
                
              default:
                  System.out.println("Invalid choice");
                   System.out.println("Please enter the valid choice");
                   getupdates();
                    
       }
   }

   public static int total_price() {
      
       int total_price=0;
       for (Entry<String, Item> entry : map.entrySet()) {
                  
                   Item it=map.get(entry.getKey());
                  
                   total_price+=it.getPrice()*it.get_quantity();
                  
               }
         
       return total_price;
      
   }
  
  
     
  
   private static void checkbudget() {
      
       System.out.print("Enter your Total Budget : ");
       int budget=s.nextInt();
      
       int totalprice=0;
  


System.out.println("Total Amount = "+total_price());

while(budget<total_price()) {
   totalprice = remove_unspecified_data();
     
     
     
   if(budget>=totalprice) {
       break;
   }
}


System.out.println();

System.out.println("Now updates cart : ");

checkout();

System.out.println();
      
   }

   private static void checkout() {
       System.out.println(" Here list of Items in Your Cart");
      
       int i=1;
       int total_price=0;
       System.out.println(" S.no Name of item Quantity price ");
       System.out.println(" ");
       for (Entry<String, Item> entry : map.entrySet()) {
          
           Item it=map.get(entry.getKey());
          
           System.out.println(" "+i+" "+entry.getKey()+" "+it.get_quantity()+" $"+it.getPrice()*it.get_quantity());
           total_price+=it.getPrice()*it.get_quantity();
           i++;
       }
      
       System.out.println();
      
       System.out.println("Total Amount = "+total_price);
      
       System.out.println();
       System.out.println();
   }

   private static int remove_unspecified_data() {
      
       System.out.print("Enter the item you want to remove from your cart : ");
       String name=s.next();
      
       Item it1=map.get(name);
      
       int quant=it1.get_quantity();
      
       if(quant>1) {
          
       quant--;
       it1.set_quantity(-1);
      
       map.put(name, it1);
       }
         
       else {
           map.remove(name, it1);
       }
      
       int total_price=total_price();
         
       total_price-=it1.getPrice();
         
       System.out.println();
       System.out.println();
      
       return total_price;
      
   }

   private static void Add_multiples_items() {
       System.out.print("Enter the item you want to add in your cart : ");
       String name=s.next();
      
System.out.println("Enter price of Item : ");
      
       int price=s.nextInt();
      
       System.out.print("Enter the quantity of that item you want to add : ");
       int quan=s.nextInt();
      
       if(map.containsKey(name)) {
           Item it1=map.get(name);
           it1.set_quantity(quan);
           map.put(name, it1);
       }
       else {
           Item it= new Item(name,price,quan);
           map.put(name, it);
       }
      
       System.out.println();
       System.out.println();
      
   }

   private static void add_new_item() {
       System.out.print("Enter the item you want to add in your cart : ");
      
       String name=s.next();
      
       System.out.println("Enter price of Item : ");
      
       int price=s.nextInt();
      
      
      
       if(map.containsKey(name)) {
           Item it1=map.get(name);
           it1.set_quantity(1);
           map.put(name, it1);
       }
       else {
           Item it= new Item(name,price,1);
           map.put(name, it);
       }
      
       System.out.println();
       System.out.println();
      
   }
  
  

}

class Item
{   
private String name;
private int price;
private int quantity; //in cents
  
//Constructor
public Item(String n, int p,int quantity)
{
name = n;
price = p;
this. quantity=quantity;
}
  
public boolean equals(Item other)
{
return this.name.equals(other.name) && this.price == other.price;
}
  
//displays name of item and price in properly formatted manner
public String toString()
{
return name + ", price: $" + price/100 + "." + price%100;
}
  
//Getter methods
public int getPrice()
{
return price;
}
  
public int get_quantity()
{
return quantity;
}
  
public void set_quantity(int qa)
{
   quantity+=qa;
}
  
public String getName()
{
return name;
}
}

Solutions

Expert Solution

Hope these comments will help you understand the code better.

import java.util.HashMap;
import java.util.Scanner;
import java.util.Map.Entry;

public class Shopping_cart {

    static Scanner s= new Scanner (System.in);

    //   declare hashmap in which key is dates as per mentioned and Values class as value which consists all the record of cases
    // map here will function as the cart. An item added will be included in the map and will be accessed through the map only
    // map functions as a cart for the program
    static HashMap<String,Item> map= new HashMap<>();

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        getupdates();
    }

    static void getupdates() {

        System.out.println("Welcome to Shopping Cart. Enter:");
        System.out.println("1 : Add an Item ");
        System.out.println("2 : Add multiples Quantities of Given Item ");
        System.out.println("3 : Remove an unspecified Item ");
        System.out.println("4 : CheckOut");
        System.out.println("5 : Checkbudget");
        System.out.print("Choice: ");
        int selection= s.nextInt();
        
        // After taking input, switch() will pick up the case corresponding to the number you have entered
        switch(selection) {
            case 1:
                add_new_item();
                getupdates();
                break;

            case 2:
                Add_multiples_items();
                getupdates();
                break;

            case 3:
                remove_unspecified_data();
                getupdates();
                break;

            case 4:
                checkout();
                getupdates();
                break;

            case 5:

                checkbudget();
                getupdates();
                break;

            case 6:
                System.out.println("Stay Safe");
                break;

            default:
                System.out.println("Invalid choice");
                System.out.println("Please enter the valid choice");
                getupdates();

        }
    }

    // returns the total price in the cart
    public static int total_price() {

        int total_price=0;
        //for each entry in the map, iterate over the map and add the price in the total price 
        for (Entry<String, Item> entry : map.entrySet()) {

            Item it=map.get(entry.getKey());

            total_price+=it.getPrice()*it.get_quantity();

        }

        return total_price;

    }




    /*
    * This function checks the your budget and if it is less than the final price of checkout, then it wil ask
    * you to remove certain items from the cart
    * */
    private static void checkbudget() {

        System.out.print("Enter your Total Budget : ");
        int budget=s.nextInt();

        int totalprice=0;



        System.out.println("Total Amount = "+total_price());

        //if budget is less than total price in cart, then remove the items from the cart
        while(budget<total_price()) {
            totalprice = remove_unspecified_data();
            
            if(budget>=totalprice) {
                break;
            }
        }


        System.out.println();

        System.out.println("Now updates cart : ");

        checkout();

        System.out.println();

    }

    // prints the details of all the items in the map and return the total price of checkout
    private static void checkout() {
        System.out.println(" Here list of Items in Your Cart");

        int i=1;
        int total_price=0;
        System.out.println(" S.no Name of item Quantity price ");
        System.out.println(" ");
        // iterate over the map and print details of each item
        for (Entry<String, Item> entry : map.entrySet()) {

            Item it=map.get(entry.getKey());

            System.out.println(" "+i+" "+entry.getKey()+" "+it.get_quantity()+" $"+it.getPrice()*it.get_quantity());
            total_price+=it.getPrice()*it.get_quantity();
            i++;
        }

        System.out.println();

        System.out.println("Total Amount = "+total_price);

        System.out.println();
        System.out.println();
    }

    //removes 1 quantity of item from the cart. If there is only 1 quantity available then it removes the complete item from list
    // and returns the total price available in the cart
    private static int remove_unspecified_data() {

        System.out.print("Enter the item you want to remove from your cart : ");
        String name=s.next();

        Item it1=map.get(name);

        int quant=it1.get_quantity();

        // if quantity of item to be removed is more than 1 just decrease its quantity
        if(quant>1) {

            quant--;
            it1.set_quantity(-1);

            map.put(name, it1);
        }

        // if the quantity is 1, remove the item from the map
        else {
            map.remove(name, it1);
        }

        // get the new total price after updation
        int total_price=total_price();

        total_price-=it1.getPrice();

        System.out.println();
        System.out.println();

        return total_price;

    }

    //this function adds item with more than 1 quantity
    private static void Add_multiples_items() {
        System.out.print("Enter the item you want to add in your cart : ");
        String name=s.next();

        System.out.println("Enter price of Item : ");

        int price=s.nextInt();

        System.out.print("Enter the quantity of that item you want to add : ");
        int quan=s.nextInt();

        // if the item is already available in map, then just update its quantity and put back in map
        if(map.containsKey(name)) {
            Item it1=map.get(name);
            it1.set_quantity(quan);
            map.put(name, it1);
        }
        //if item is not in the map then create the instance of item and add it in the map
        else {
            Item it= new Item(name,price,quan);
            map.put(name, it);
        }

        System.out.println();
        System.out.println();

    }

    //this function adds only single quantity item
    private static void add_new_item() {
        System.out.print("Enter the item you want to add in your cart : ");

        String name=s.next();

        System.out.println("Enter price of Item : ");

        int price=s.nextInt();

        // if the item is already available in map, then just update its quantity and put back in map
        if(map.containsKey(name)) {
            Item it1=map.get(name);
            it1.set_quantity(1);
            map.put(name, it1);
        } //if item is not in the map then create the instance of item and add it in the map
        else {
            Item it= new Item(name,price,1);
            map.put(name, it);
        }

        System.out.println();
        System.out.println();

    }



}

/*
* This class is the structure defination of how the item structure will look. It contains name (the name of item), price (price
* of the item) and quantity (its quantity).
* @equal(Item other) : returns if one Item is equal to another
* @toString() : return the parameters of class Item in string format.
* */
class Item
{
    private String name;
    private int price;
    private int quantity; //in cents

    //Constructor
    public Item(String n, int p,int quantity)
    {
        name = n;
        price = p;
        this. quantity=quantity;
    }

    public boolean equals(Item other)
    {
        return this.name.equals(other.name) && this.price == other.price;
    }

    //displays name of item and price in properly formatted manner
    public String toString()
    {
        return name + ", price: $" + price/100 + "." + price%100;
    }

    //Getter methods
    public int getPrice()
    {
        return price;
    }

    public int get_quantity()
    {
        return quantity;
    }

    public void set_quantity(int qa)
    {
        quantity+=qa;
    }

    public String getName()
    {
        return name;
    }
}

Related Solutions

Can you please take this code and just rewrite it so it can be easily be...
Can you please take this code and just rewrite it so it can be easily be able to put into a complier. in java Implementation of above program in java: import java.util.HashMap; import java.util.Scanner; import java.util.Map.Entry; public class Shopping_cart {       static Scanner s= new Scanner (System.in);    //   declare hashmap in which key is dates as per mentioned and Values class as value which consists all the record of cases    static HashMap<String,Item> map= new HashMap<>();    public...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog {...
Can you please add comments to this code? JAVA Code: import java.util.ArrayList; public class Catalog { String catalog_name; ArrayList<Item> list; Catalog(String cs_Gift_Catalog) { list=new ArrayList<>(); catalog_name=cs_Gift_Catalog; } String getName() { int size() { return list.size(); } Item get(int i) { return list.get(i); } void add(Item item) { list.add(item); } } Thanks!
Please I can get a flowchart and a pseudocode for this java code. Thank you //import...
Please I can get a flowchart and a pseudocode for this java code. Thank you //import the required classes import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BirthdayReminder {       public static void main(String[] args) throws IOException {        // declare the required variables String sName = null; String names[] = new String[10]; String birthDates[] = new String[10]; int count = 0; boolean flag = false; // to read values from the console BufferedReader dataIn = new BufferedReader(new...
Can someone please convert this java code to C code? import java.util.LinkedList; import java.util.List; public class...
Can someone please convert this java code to C code? import java.util.LinkedList; import java.util.List; public class Phase1 { /* Translates the MAL instruction to 1-3 TAL instructions * and returns the TAL instructions in a list * * mals: input program as a list of Instruction objects * * returns a list of TAL instructions (should be same size or longer than input list) */ public static List<Instruction> temp = new LinkedList<>(); public static List<Instruction> mal_to_tal(List<Instruction> mals) { for (int...
I wrote this code and it produces a typeError, so please can you fix it? import...
I wrote this code and it produces a typeError, so please can you fix it? import random def first_to_a_word(): print("###### First to a Word ######") print("Instructions:") print("You will take turns choosing letters one at a time until a word is formed.") print("After each letter is chosen you will have a chance to confirm whether or not a word has been formed.") print("When a word is formed, the player who played the last letter wins!") print("One of you has been chosen...
Please can I get a flowchart and pseudocode for this java code. Thank you. TestScore.java import...
Please can I get a flowchart and pseudocode for this java code. Thank you. TestScore.java import java.util.Scanner; ;//import Scanner to take input from user public class TestScore {    @SuppressWarnings("resource")    public static void main(String[] args) throws ScoreException {//main method may throw Score exception        int [] arr = new int [5]; //creating an integer array for student id        arr[0] = 20025; //assigning id for each student        arr[1] = 20026;        arr[2] = 20027;...
Please can I kindly get a flowchart for this java code. Thank you. //import the required...
Please can I kindly get a flowchart for this java code. Thank you. //import the required classes import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class BirthdayReminder {       public static void main(String[] args) throws IOException {        // declare the required variables String sName = null; String names[] = new String[10]; String birthDates[] = new String[10]; int count = 0; boolean flag = false; // to read values from the console BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in));...
please right make it so that it can run on jGRASP and java code please thank...
please right make it so that it can run on jGRASP and java code please thank you Debug Problem 1: As an intern for NASA, you have been instructed to debug a java program that calculates the speed that sound travels in water. Details about the formulas and correct results appear in the comments area at the top of the program Here is the code to debug: importjava.util.Scanner; /**    This program demonstrates a solution to the    The Speed of Sound...
This is an entry to Java Question. Please answer with Pseudocode and Java code for better...
This is an entry to Java Question. Please answer with Pseudocode and Java code for better understanding. We are mainly using basic in and out declarations and are focusing on API for method invocations. Any help would be very appreciated :) Problem 7: Distance (10 points) Use API (Data Science) Data Science is an emergent field from Computer Science with applications in almost every domain including finances, medical research, entertainment, retail, advertising, and insurance. The role of a data analyst...
please write the java code so it can run on jGRASP Thanks! CODE 1 1 /**...
please write the java code so it can run on jGRASP Thanks! CODE 1 1 /** 2 * SameArray2.java 3 * @author Sherri Vaseashta4 * @version1 5 * @see 6 */ 7 import java.util.Scanner;8 public class SameArray29{ 10 public static void main(String[] args) 11 { 12 int[] array1 = {2, 4, 6, 8, 10}; 13 int[] array2 = new int[5]; //initializing array2 14 15 //copies the content of array1 and array2 16 for (int arrayCounter = 0; arrayCounter < 5;...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT