Start learning free

LESSON 189 OF 671 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V4 in Java: Cart Sum with a for Loop and Parallel Arrays

Practice Read the full explanation

Use a for loop over parallel arrays to compute a running total across several items.

You start with:

String[] items = {"Shirt", "Pants", "Shoes", "Hat"};
int[] prices = {25, 40, 60, 15};
int[] quantities = {2, 1, 1, 3};

Build:

Shirt x2: $50
Pants x1: $40
Shoes x1: $60
Hat x3: $45
Total: $195

Rules:

  • For each index i, the item's subtotal is prices[i] * quantities[i].
  • Build one line per item, in order, in the format "Name xQ: $subtotal" (e.g. "Shirt x2: $50").
  • Add every subtotal to a running total.
  • Finish with a "Total: $..." line.
  • Join all the lines with a newline "\n" into one string result, then print it with System.out.println(result).

Use List<String> lines = new ArrayList<>(); and an int total = 0; before the loop, then add each formatted line.

Call String.join("\n", lines) at the end.

String[] items = {"Shirt", "Pants", "Shoes", "Hat"};
int[] prices = {25, 40, 60, 15};
int[] quantities = {2, 1, 1, 3};

List<String> lines = new ArrayList<>();
int total = 0;
for (int i = 0; i < items.length; i++) {
    int sub = prices[i] * quantities[i];
    total = total + sub;
    lines.add(items[i] + " x" + quantities[i] + ": $" + sub);
}
lines.add("Total: $" + total);
String result = String.join("\n", lines);
System.out.println(result);

STEP 1 OF 9
    Ctrl + Enter to check

    JAVA · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V4 in Java, explained

    Problem overview

    This version prints a receipt for a cart with several items. The data comes in three parallel arrays: items holds the names, prices the unit prices and quantities how many of each were bought. Position i in the three arrays describes the same item, so "Shirt", 25 and 2 belong together.

    For each item the program prints one line in the format Name xQ: $subtotal, where the subtotal is the price times the quantity. A final line shows the total of all subtotals. For the starter data the output is:

    Shirt x2: $50
    Pants x1: $40
    Shoes x1: $60
    Hat x3: $45
    Total: $195

    The result is built as one string, result, and printed once with System.out.println.

    Approach: one pass with a running total

    The same few operations repeat for every item: multiply, add to a sum and format a row. A for loop that walks the positions 0 to items.length - 1 does this once for each item, whatever the number of items.

    Two things live outside the loop. The running total is an int that starts at 0 and grows by each subtotal. The rows go into a List<String>, because an array has a fixed size while a list grows with each add. The receipt has one row per item plus the total row, and a list fits rows that arrive one at a time.

    Because the arrays are parallel, the loop uses an index rather than reading the items directly: prices[i] and quantities[i] are only meaningful together with items[i].

    Step by step

    1. Create the list lines: a List<String> holding a new, empty ArrayList. Declaring the variable as the interface type List is the usual style.
    2. Create total at 0. A running total starts at zero, before any item is counted.
    3. Write the loop. i starts at 0 and stays below items.length, so it takes the values 0, 1, 2 and 3 for four items.
    4. Compute sub, the subtotal of the current item: prices[i] * quantities[i].
    5. Add sub to total.
    6. Add the row. The row is built from the name, a space and x, the quantity, a colon, a space, the dollar sign and sub, joined with +.
    7. After the loop, add the total row. It sits outside the braces so it runs once, not once per item.
    8. Join the rows. String.join("\n", lines) puts a newline between each two elements of the list, and none after the last.
    9. Print result.

    The solution in Java

    String[] items = {"Shirt", "Pants", "Shoes", "Hat"};
    int[] prices = {25, 40, 60, 15};
    int[] quantities = {2, 1, 1, 3};
    
    List<String> lines = new ArrayList<>();
    int total = 0;
    for (int i = 0; i < items.length; i++) {
        int sub = prices[i] * quantities[i];
        total = total + sub;
        lines.add(items[i] + " x" + quantities[i] + ": $" + sub);
    }
    lines.add("Total: $" + total);
    String result = String.join("\n", lines);
    System.out.println(result);
    

    The Java details worth a closer look:

    • Arrays versus lists. items.length is a field, with no parentheses, while a list reports its size with the method lines.size(). An array literal such as {"Shirt", "Pants"} can only be used in a declaration like the starter's, and an array cannot grow. That is why the rows go into an ArrayList.
    • Imports. List and ArrayList live in java.util. In a standalone Java file you need import java.util.*; at the top.
    • The diamond <>. In new ArrayList<>() the compiler fills in String from the variable's type.
    • String.join. The first argument is the separator and the second is any collection of strings, here a List<String>. Because the separator goes only between elements, there is no extra newline to trim.
    • total = total + sub has the same effect as total += sub.
    • Numbers inside text. In items[i] + " x" + quantities[i] + ": $" + sub the + operators work left to right. The left side is already a String from the first step, so each int is converted to text as it is joined.

    Complexity

    Time: O(n) for n items. The loop body does a constant amount of work for each item, and String.join visits each row once.

    Space: O(n). The list holds one string per item, and the final string holds all of them.

    Edge cases and common mistakes

    • Adding the total row inside the loop. The receipt would end up with a Total line after every item. It belongs after the closing brace.
    • Starting total at the wrong value. A running sum starts at 0. Declaring it inside the loop resets it on every pass, so only the last subtotal would remain.
    • Looping with i <= items.length. The last pass reads items[4] and throws an ArrayIndexOutOfBoundsException.
    • Arrays of different lengths. The loop trusts items.length. If prices or quantities were shorter, the loop would fail with the same exception, so keep the three arrays in step.
    • A quantity of 0. The row is still added. A Hat with quantity 0 prints Hat x0: $0 and adds nothing to the total.
    • No items at all. With empty arrays the loop never runs, and the output is just Total: $0.
    • Using + to build one big string. You could append "\n" to a string in the loop, but then the last row ends with an extra newline unless you remove it. Collecting rows in a list and joining them avoids the problem.

    Testing

    • The starter arrays give the five-line receipt shown above, ending in Total: $195.
    • A single item Hat with price 15 and quantity 0 gives Hat x0: $0 then Total: $0.
    • Three empty arrays give just Total: $0.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free