Problem overview
The cart now holds several items. Three arrays run in parallel: items has the names, prices the unit prices and quantities how many of each. Position i in all three describes the same item. The program prints one receipt row per item, in the format Name xQ: $subtotal, where the subtotal is the price times the quantity, followed by a Total row that adds up every subtotal.
For Array("Shirt", "Pants", "Shoes", "Hat"), prices Array(25, 40, 60, 15) and quantities Array(2, 1, 1, 3) the output is:
Shirt x2: $50
Pants x1: $40
Shoes x1: $60
Hat x3: $45
Total: $195
The earlier versions handled one number at a time. This one introduces a loop that does the same work for every item, and a running total that grows as it goes.
Approach: loop by position, collect rows, sum as you go
Because the data sits in parallel arrays, the natural loop is over positions. items.indices is the range of valid positions, 0 up to the last one, so i takes the values 0, 1, 2, 3 and indexes all three arrays together. Each pass does three small things: compute the item's subtotal, add it to the running total, and record the row.
The rows need somewhere to live until the end. A Scala Array has a fixed size, and a List is immutable, so the lesson uses an ArrayBuffer[String], a growable list. It is a val because the program only adds to the buffer and never replaces it. The total, on the other hand, is a var, because a new value is stored in it on every pass.
The Total row belongs after the loop. It must run once, after every subtotal has been added, not once per item.
Step by step
- Create
lines, an emptyscala.collection.mutable.ArrayBuffer[String]. The full name is needed because the mutable collections are not imported by default. - Create
totalas avarstarting at 0. It is the running sum. - Write the loop
for (i <- items.indices), with its closing brace right away. The steps below go inside it. - Compute
sub, this item's subtotal:prices(i) * quantities(i). Scala indexes arrays with parentheses, not square brackets. - Add
subtototal. - Append the row with
lines.append: the name, a space andxwith the quantity, a colon, then$and the subtotal. - After the loop, append the
Totalrow. - Build
resultwithlines.mkString("\n"). The argument is put between each two elements, so there is no newline after the last row. - Print
resultwithprintln.
The solution in Scala
val items = Array("Shirt", "Pants", "Shoes", "Hat")
val prices = Array(25, 40, 60, 15)
val quantities = Array(2, 1, 1, 3)
val lines = scala.collection.mutable.ArrayBuffer[String]()
var total = 0
for (i <- items.indices) {
val sub = prices(i) * quantities(i)
total = total + sub
lines.append(items(i) + " x" + quantities(i) + ": $" + sub)
}
lines.append("Total: $" + total)
val result = lines.mkString("\n")
println(result)
Details that matter here:
- Parentheses for indexing.
prices(i)is a method call on the array, while square brackets in Scala are for type arguments such as the[String]inArrayBuffer[String]. - String plus
Int. Initems(i) + " x" + quantities(i) + ": $" + subeach+has aStringon its left, so the numbers are converted to text as they are joined. The expression is evaluated left to right. valwith a mutable object.val linesmeans the name always points to the same buffer. The buffer's contents can still change, which is whatappenddoes.items.indicesis the same as0 until items.length. It avoids writing the length by hand, so the loop follows the array if the cart grows.mkStringworks on any collection and takes the separator. It is the usual way to join rows without a trailing separator.
Following the loop
For the starting data, the loop passes through four states. After the Shirt pass total is 50, after Pants 90, after Shoes 150 and after Hat 195. The last number is what the Total row prints. Each pass also adds exactly one row to lines, so by the end the buffer has five rows: four items and the total.
Edge cases and common mistakes
- Quantity 0. An item with quantity 0 still gets a row, with a subtotal of 0. For
Array("Pen"), price 3 and quantity 0, the output isPen x0: $0andTotal: $0. - Empty cart. With empty arrays the loop never runs, and the only row is
Total: $0. - Arrays of different lengths. The loop follows
items.indices, so a shorterpricesorquantitiesarray would throw anArrayIndexOutOfBoundsExceptionat the first missing position. The three arrays must describe the same items. - Putting the
Totalrow inside the loop. That prints a total after every item instead of one at the end. - Replacing instead of adding. Writing
total = subkeeps only the last subtotal. The line has to readtotal = total + sub, or the shortertotal += sub.
Testing
A cart of one pen (price 3, quantity 0) and an empty cart both produce the outputs shown above. Try changing a quantity in the editor above and check that both the row and the total follow. The next version builds on this program.
