Java
Calculating totals
Compute subtotal and tax-inclusive total.
Calculating totals
In this lesson we'll sum the prices of the items in the cart. Prices are kept in an ArrayList<Double>; a for-each loop computes the total:
ArrayList<Double> prices = new ArrayList<>();
prices.add(10.0);
prices.add(20.0);
double subtotal = 0;
for (double price : prices) {
subtotal += price;
}
System.out.println(subtotal); // 30.0
subtotal += price adds price to subtotal at each iteration. This is the basic method for list sums.
Tax-inclusive total
The tax-inclusive total is subtotal + (subtotal * taxRate). For example with 10% tax:
double subtotal = 30.0;
double tax = subtotal * 0.10; // 3.0
double total = subtotal + tax; // 33.0
System.out.println("Total: " + total);
Here tax is the tax amount, total is what the user pays including tax. The tax rate is written as a decimal like 0.10; no percent sign.
Exercise Subtotal and tax-inclusive total
Add to the previous lesson's code: define ArrayList<Double> prices, add 10.0 and 20.0. Compute double subtotal with for (double price : prices). Set double tax = subtotal * 0.10, double total = subtotal + tax. Print "Subtotal: " + subtotal, "Tax: " + tax, "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");
System.out.println(cart);
System.out.println(cart.size());
ArrayList<Double> prices = new ArrayList<>();
prices.add(10.0);
prices.add(20.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("Tax: " + tax);
System.out.println("Total: " + total);
}
}
Test yourself
-
What is the sum of prices = [10.0, 20.0]?
Show answer
30.0 — 10.0 + 20.0 = 30.0.
-
Complete the total loop
double subtotal = 0;
for (double price : prices) {
subtotal ____ price;
}
Show answer
double subtotal = 0;
for (double price : prices) {
subtotal += price;
}
-
Match the total concepts
- subtotal
- Subtotal
- tax
- Tax
- total
- Tax inclusive
- +=
- Addition assignment
Next lesson: Updating quantity