Write a class called Item that has a string field called name and a double field called price and an integer field called quantity. In main, create a bag of type Item and place several item objects in the bag. Then in main calculate the total price of items purchased. You may remove each item and add the price to a total variable in a loop. The loop should end when the bag is empty.
The code will be
import java.util.*;
public class Item {
private String name;
private double price;
private int quantity;
public Item(String n,double p,int q){
name=n;
price=p;
quantity=q;
}
public static void main(String args[]) {
ArrayList<Item> arr=new ArrayList<Item>();
arr.add(new Item("a",1,2));
arr.add(new Item("b",2,2));
arr.add(new Item("c",3,2));
arr.add(new Item("d",4,2));
double total=0.0;
for(Item i:arr){
total+=i.price;
}
System.out.println(total);
}
}
The output is
10.0
Get Answers For Free
Most questions answered within 1 hours.