In: Computer Science
In Java:
(1) Create two files to submit:
Build the ItemToBuy class with the following specifications:
(2) In main(), prompt the user for two items and create two objects of the ItemToPurchase class. Before prompting for the second item, call scnr.nextLine(); to allow the user to input a new string.
Ex:
Item 1
Item = Chocolate Chips, Price = 3, Quantity = 1
Item 2
Item = Bottled Water, Price = 1, Quantity = 10
(3) Add the costs of the two items together and output the total cost. (2 pts)
TOTAL COST Chocolate Chips 1 @ $3 = $3
Bottled Water 10 @ $1 = $10
Total: $13
package items;
import java.util.*;
public class ItemToBuy//public class
{
public String itemName ;//data members
public int itemPrice;
public int itemQuantity;
Scanner sc=new Scanner(System.in);
public ItemToBuy()//functions
{
itemName="none";
itemPrice=0;
itemQuantity=0;
}
public void setName()
{
itemName=sc.nextLine();
}
public String getname()
{
return itemName;
}
public void setprice()
{
itemPrice=sc.nextInt();
}
public int getprice()
{
return itemPrice;
}
public void setquantity()
{
itemQuantity=sc.nextInt();
}
public int getquantity()
{
return itemQuantity;
}
}
save this file make it a packge by
javac -d . ItemToBuy.java
this above command in command prompt
import items.ItemToBuy;//imporing the class
class ShoppingCartDriver
{
public static void main(String[] args) {
ItemToBuy obj=new ItemToBuy();//making the 2 objects
ItemToBuy obj1=new ItemToBuy();
System.out.println("item 1");//input from the user
System.out.println("enter name");
obj.setName();
System.out.println("enter price");
obj.setprice();
System.out.println("enter quantity");
obj.setquantity();
System.out.println("item 2");
System.out.println("enter name");
obj1.setName();
System.out.println("enter price");
obj1.setprice();
System.out.println("enter quantity");
obj1.setquantity();
System.out.println("Total cost"+obj.getname()+obj.getquantity()+"@ $"+obj.getprice());
int i1=obj.getprice()*obj.getquantity();
System.out.println(i1);
System.out.println("Total cost"+obj1.getname()+obj1.getquantity()+"@ $"+obj1.getprice());
int i2=obj1.getprice()*obj1.getquantity();
System.out.println(i2);
int total=i1+i2;//total price calculation
System.out.println("total= $"+total);
}
}
output:
item 1
enter name
Chocolate Chips
enter price
1
enter quantity
3
item 2
enter name
Bottled Water
enter price
1
enter quantity
3
Total costChocolate Chips3@ $1
3
Total costBottled Water3@ $1
3
total= $6