java · level 2 · unit 1 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Lists hold objects, so numbers travel in a wrapper.
Angle brackets only take classes, and int is not a class. Put int between them and Java stops with unexpected type. Each plain type has a to use instead: for int, Double for double and Boolean for boolean.
You will hardly notice the wrapper. scores.add(7) wraps the 7 for you, and int first = scores.get(0); unwraps it again. This is called : Java pops the number in a little box and takes it out when you need it.
A for-each loop works on a list the same way it works on an array, so a running total looks the same as before.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> scores = new ArrayList<>();
scores.add(7);
scores.add(12);
scores.add(5);
int total = 0;
for (int score : scores) {
total = total + score;
}
System.out.println(scores + " add up to " + total);
}
} Integer and Double start with a capital letter, because they are classes.
guess first
Decimal prices in a list. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Double> prices = new ArrayList<>();
prices.add(1.5);
prices.add(2.25);
prices.add(3.0);
double total = 0;
for (double price : prices) {
total = total + price;
}
System.out.println(prices.size() + " items cost " + total);
}
}
your turn
Your turn. Find your best day.
Add three daily step counts, as whole numbers, on lines 5 to 7. Then press run to find your best day.
output
press run to see what happens
fix it
This list of ages will not even start. Fix it!
output
press run to see what happens
- Java says
unexpected typeon line 4. Look between the angle brackets. - Angle brackets only take classes.
intis a plain type, so it needs its wrapper class. - Change the
intbetween the angle brackets toIntegeron line 4, then press run.
nailed it
you wrapped numbers and kept them in a list. :D
- Angle brackets take classes, so write
Integer, notint. - Autoboxing wraps and unwraps numbers for you.
- A for-each loop works on lists too.
new words in your collection
- wrapper class
- Integer
- autoboxing
This lesson isn’t saved. A free account remembers every lesson you finish.