☰ Contents Collecting Values

Counter as an Index

Student: I could use some more practice and ideas with arrays.
Prof: Glad you asked. Let’s see how to combine a counter and a running total to do something cool with an array.
Student: I’m game

Prof: Let’s imagine we want to print an array of strings, but numbered. So we have {"apple", "banana"} and we want to print it as

1. apple
2. banana
Student: I can see that being useful.
Prof: So we’ll set it up as a record with a field that’s a String[], and then a method that builds this numbered string. One thing I need to mention first – "\n" means “newline” in Java. It’s a escape character that has a special meaning. It won’t print as \n, it’ll make the rest of the string go onto the next line when printed.
Student: Alright, I’ll be ready for it.
Student: I see the \n, that is making them show up on separate lines. And when you do + counter that’s concatenating the number in?
Prof: That’s right. So this example is really using two loop patterns together. The counter is always increasing by 1 in this case (not conditionally like in our other counters), and it’s used as part of the accumulated result.

Practice

Trace groceries.numberedList(). For each run of the loop body, fill in counter as the body starts, and the line the body adds to result.
item is "eggs": counter is , and the body adds
item is "milk": counter is , and the body adds
item is "bread": counter is , and the body adds
After the loop, counter is .