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
- Create the list
lines: aList<String>holding a new, emptyArrayList. Declaring the variable as the interface typeListis the usual style. - Create
totalat 0. A running total starts at zero, before any item is counted. - Write the loop.
istarts at 0 and stays belowitems.length, so it takes the values 0, 1, 2 and 3 for four items. - Compute
sub, the subtotal of the current item:prices[i] * quantities[i]. - Add
subtototal. - Add the row. The row is built from the name, a space and
x, the quantity, a colon, a space, the dollar sign andsub, joined with+. - After the loop, add the total row. It sits outside the braces so it runs once, not once per item.
- Join the rows.
String.join("\n", lines)puts a newline between each two elements of the list, and none after the last. - 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.lengthis a field, with no parentheses, while a list reports its size with the methodlines.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 anArrayList. - Imports.
ListandArrayListlive injava.util. In a standalone Java file you needimport java.util.*;at the top. - The diamond
<>. Innew ArrayList<>()the compiler fills inStringfrom the variable's type. String.join. The first argument is the separator and the second is any collection of strings, here aList<String>. Because the separator goes only between elements, there is no extra newline to trim.total = total + subhas the same effect astotal += sub.- Numbers inside text. In
items[i] + " x" + quantities[i] + ": $" + subthe+operators work left to right. The left side is already aStringfrom the first step, so eachintis 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
Totalline after every item. It belongs after the closing brace. - Starting
totalat 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 readsitems[4]and throws anArrayIndexOutOfBoundsException. - Arrays of different lengths. The loop trusts
items.length. Ifpricesorquantitieswere 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
Hatwith quantity 0 printsHat x0: $0and 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
Hatwith price 15 and quantity 0 givesHat x0: $0thenTotal: $0. - Three empty arrays give just
Total: $0.
