Calculating totals
- Java course
- Beginner
- Lesson 50/116
- 6 min
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.0subtotal += 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.
Practice 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.
Starter code
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());
// Add a price list and compute subtotal and tax-inclusive total
}
}Sample 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);
}
}Expected output
[Apple, Bread] 2 Subtotal: 30.0 Tax: 3.0 Total: 33.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the sum of prices = [10.0, 20.0]?
- 20.0
- 10.0
- 30.0 Correct answer
- 200.0
Explanation: 10.0 + 20.0 = 30.0.
2 Complete the total loop
double subtotal = 0;
for (double price : prices) {
subtotal ____ price;
}
double subtotal = 0;
for (double price : prices) {
subtotal += price;
}
Explanation: += adds price to subtotal at each iteration.
3 Match the total concepts
| Term | Meaning |
|---|---|
subtotal |
Subtotal |
tax |
Tax |
total |
Tax inclusive |
+= |
Addition assignment |