PROGRAM 1 – Shopper Calculator
You must write a small application in JAVA that can assist a shopper by calculating the total price of the items that he or she wants to buy and displaying a tillslip-like list of the products, their prices and the total due.
Your program must
1. Read the name and price of five items as input.
2. Calculate the total price for the items.
3. Display all the item names and prices.
4. Display the total due for all items.
import java.util.Scanner;
import com.sun.org.apache.xalan.internal.xsltc.compiler.sym;
class Item {
private String name;
private double price;
public Item() {
}
public Item(String name, double price) {
this.name = name;
this.price = price;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the price
*/
public double getPrice() {
return price;
}
/**
* @param price the price to set
*/
public void setPrice(double price) {
this.price = price;
}
}
class App {
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
Item items[] = new Item[5];
double totalPrice = 0;
// 1. Read the name and price of five items as input.
for (int i = 0; i < 5; i++) {
System.out.print("Enter the name of the item " + (i + 1) + ": ");
String name = keyBoard.nextLine();
System.out.print("Enter the price of the item " + (i + 1) + ": ");
double price = keyBoard.nextDouble();
// 2. Calculate the total price for the items.
totalPrice += price;
items[i] = new Item(name, price);
keyBoard.nextLine();
}
// 3. Display all the item names and prices.
System.out.printf("%-15s%-10s\n", "Name", "Price");
for (int i = 0; i < 5; i++) {
System.out.printf("%-15s%-10.2f\n", items[i].getName(), items[i].getPrice());
}
// 4. Display the total due for all items.
System.out.println("The total due for all items: " + totalPrice);
keyBoard.close();
}
}
Comments
Leave a comment