java · level 1 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A visits every item in an array.
A for-each loop hands you each item in turn, from first to last. for (int price : prices) reads as: for each int called price in prices, run the block.
The loop box gets the next item on every turn. No counting, no index, and it can never fall off the end of the array.
To add things up, keep a . Make a box holding 0 before the loop, then add each item to it inside the block, like a till adding up your shopping.
public class Main {
public static void main(String[] args) {
int[] prices = {3, 5, 2};
int total = 0;
for (int price : prices) {
total = total + price;
}
System.out.println("Total: " + total);
}
} Read the colon in a for-each loop as in.
guess first
Step by step. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
public static void main(String[] args) {
int[] dailySteps = {3000, 4000, 2000};
int total = 0;
for (int steps : dailySteps) {
total = total + steps;
System.out.println(total);
}
}
}
your turn
Your turn. Add up your shopping.
Type three prices on line 3 as whole numbers, then press run to add them up.
output
press run to see what happens
fix it
The total is only the last score. Can you fix it?
output
press run to see what happens
- The total ends up as 4, the last score. What happens to total on each turn?
- Line 6 overwrites total every time instead of adding to it.
- Change line 6 to
total = total + score;, then press run.
nailed it
you added up a whole array. :D
- A for-each loop visits every item in order.
- Read
for (int price : prices)as for each price in prices. - Start a running total at 0 and add each item.
new words in your collection
- for-each loop
- running total
This lesson isn’t saved. A free account remembers every lesson you finish.