In: Computer Science
Define a class Product to hold the name and price of items in a grocery store. Encapsulate the fields and provide getters and setters. Create an application for a grocery store to calculate the total bill for each customer. Such program will read a list of products purchased and the quantity of each item. Each line in the bill consists of: ProductName ProductPrice Quantity/Weight
The list of items will be terminated by the “end” keyword. The data will look like this: Juice 10 7 Apples 3 3.5 Cereal 5 3 Gum 1 15 Pears 3.5 5 ends The program should read the data from the console, calculate the total price of the items purchased and print it out. For each line create an object of class Product and initialize its fields in the constructor. Then calculate the price for given quantity using the getter of the object.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
import java.util.StringTokenizer;
public class product {
String name;
float price;
float quantity;
static ArrayList<product> productList=new ArrayList<product>(); //contains all products and their details
//constructor
public product(String name,float price, float quantity) {
this.name=name;
this.price=price;
this.quantity=quantity;
}
//getter and setter functions
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public float getQuantity() {
return quantity;
}
public void setQuantity(float quantity) {
this.quantity = quantity;
}
public static void main(String[] args) {
float totalPrice=0;
String input;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the product name, product price and quantity of the product:");
while(true) {
input=sc.nextLine();
if(input.equalsIgnoreCase("end"))
break; //terminate the loop and stop taking more inputs
else {
StringTokenizer st=new StringTokenizer(input, " ");
//split the input line (name,price and quantity) and pass them as parameters to the constructor
product temp=new product(st.nextToken(),Float.parseFloat(st.nextToken()),Float.parseFloat(st.nextToken()));
productList.add(temp); //add the object to the list
}
}
System.out.println("Input completed");
Iterator it=productList.iterator();
while(it.hasNext()) { //iterates over the product list and calculates price of each product whcih is added to the 'totalPrice'
product temp=(product) it.next();
totalPrice+=(temp.getPrice()*temp.getQuantity());
}
System.out.println("Total bill is: "+totalPrice);
sc.close();
}
}
The java code is given above. the screenshot of the output has also been attached for your reference.
the code has been written as per the requirements given in the question. Relevant comments have been added which should help to undertsand the code.
Hope it helps.