Java Tutorial
Java Project: Shopping Cart
A cart of line items with name, quantity, and price. Print a receipt and the grand total.
What you will build
Each line has a name, quantity, and unit price. Print a receipt and the total.
Line items
Example
record Line(String name, int qty, double price) {
double total() { return qty * price; }
}
public class Main {
public static void main(String[] args) {
java.util.List cart = java.util.List.of(
new Line("Tea", 2, 3.50),
new Line("Bread", 1, 2.20),
new Line("Jam", 1, 4.00)
);
double grand = 0;
for (Line line : cart) {
System.out.printf("%s x%d %.2f%n", line.name(), line.qty(), line.total());
grand += line.total();
}
System.out.printf("total %.2f%n", grand);
}
} Practice
- Compile the complete program at
/java/try. - Change one input value and compile again.
- Replace a hardcoded number with
Scannerwhen you want typed input.