Java
Putting it together
Combine the cart class with a menu loop.
Putting the cart together
In the final lesson we combine the cart. Add a third item, list all items with for-each, add a third price and compute the total:
cart.add("Milk");
cart.set(0, "Apple x2");
cart.remove(1);
for (String item : cart) {
System.out.println(item);
}
// ... prices and total
This is the skeleton of the cart app: adding, listing and total. Listing each item shows the cart to the customer.
Exercise List all items
Add to the previous code: add a third item with cart.add("Milk") (after the first add calls). Update with cart.set(0, "Apple x2") and cart.remove(1). List all items with for (String item : cart) { System.out.println(item); }. Add a third price with prices.add(15.0). Keep the total line.
Show example solution
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cart = new ArrayList<>();
cart.add("Apple");
cart.add("Bread");
cart.add("Milk");
cart.set(0, "Apple x2");
cart.remove(1);
for (String item : cart) {
System.out.println(item);
}
ArrayList<Double> prices = new ArrayList<>();
prices.add(10.0);
prices.add(20.0);
prices.add(15.0);
double subtotal = 0;
for (double price : prices) {
subtotal += price;
}
double tax = subtotal * 0.10;
double total = subtotal + tax;
System.out.println("Subtotal: " + subtotal);
System.out.println("Total: " + total);
}
}
Exercise Full cart (3 items)
Add to the previous code: add a third item with cart.add("Milk"), update with cart.set(0, "Apple x2") and cart.remove(1). List all items with for (String item : cart) { System.out.println(item); }. Add a third price with prices.add(15.0). Print "Subtotal: " + subtotal and "Total: " + total with println.
Show example solution
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cart = new ArrayList<>();
cart.add("Apple");
cart.add("Bread");
cart.add("Milk");
cart.set(0, "Apple x2");
cart.remove(1);
for (String item : cart) {
System.out.println(item);
}
ArrayList<Double> prices = new ArrayList<>();
prices.add(10.0);
prices.add(20.0);
prices.add(15.0);
double subtotal = 0;
for (double price : prices) {
subtotal += price;
}
double tax = subtotal * 0.10;
double total = subtotal + tax;
System.out.println("Subtotal: " + subtotal);
System.out.println("Total: " + total);
}
}
Test yourself
-
What are the basic steps of the cart app?
- Add, list, total
- Open, read, close
- Print, wait, exit
- Input, process, output
Show answer
Add, list, total — The cart has adding, listing and total steps.
-
Match the cart pieces
- add
- Add an item
- for-each
- List items
- +=
- Addition
- println
- Print
-
Complete the for-each
for (String item : ____) {
System.out.println(item);
}
Show answer
for (String item : cart) {
System.out.println(item);
}
Next lesson: Declaring arrays