In: Computer Science
Goals Understand class structure and encapsulation
Description 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 “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
end
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.
/******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.util.*;
class Grocery{
public String name;
public double price;
public double quantity;
public Grocery(String name,double price,double quantity){
this.name = name;
this.price = price;
this.quantity = quantity;
}
public String getName(){
return this.name;
}
public double getPrice(){
return this.price;
}
public double getQuantity(){
return this.quantity;
}
}
public class Main{
public static void main(String []args){
double totalPrice = 0.0;
Scanner myObj = new Scanner(System.in);
System.out.println("Enter No of items purchased");
int n = Integer.parseInt(myObj.nextLine());
String name;
double price;
double quantity;
for (int i=0;i<n;i++){
System.out.println("Enter Name of item purchased");
name = myObj.nextLine();
System.out.println("Enter Price of item purchased");
price = Double.parseDouble(myObj.nextLine());
System.out.println("Enter quantity of item purchased");
quantity = Double.parseDouble(myObj.nextLine());
Grocery g1 = new Grocery(name,price,quantity);
totalPrice += g1.getPrice()*g1.getQuantity();
}
System.out.println(totalPrice);
}
}
Sample Output:
Please comment in case of doubts, Please upvote the solution