java · level 1 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Loop through an array to find what you need.
To an array, look at each item with a loop and an if. Before the loop, make a : a boolean box holding false. When you find a match, raise the flag by setting it to true.
The same trick finds the biggest item. Keep the first item in a box called best. Each time you meet a bigger one, put that in best instead.
For text items, compare with .equals, not ==.
public class Main {
public static void main(String[] args) {
String[] fridge = {"milk", "cheese", "jam"};
boolean found = false;
for (String food : fridge) {
if (food.equals("cheese")) {
found = true;
}
}
System.out.println("Cheese in the fridge: " + found);
}
} Once the flag is up, break can stop the search early.
guess first
Find the biggest. 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[] scores = {12, 30, 18};
int best = scores[0];
for (int score : scores) {
if (score > best) {
best = score;
}
}
System.out.println("Best: " + best);
}
}
your turn
Your turn. Is it on the shopping list?
Type one of the three things on the shopping list between the quotes on line 6, then press run to raise the flag.
output
press run to see what happens
fix it
The coldest day came out wrong. Fix it!
output
press run to see what happens
- It shows 0, but 0 is not even in the array. Where does 0 come from?
- coldest starts at 0, and no temperature is below 0, so it never changes. Start with a real item instead.
- Change line 4 to
int coldest = temps[0];, then press run.
nailed it
you can find anything in an array. :D
- Search with a loop, an
ifand abooleanflag. - Start
bestat the first item, then swap in bigger ones. - Compare text items with
.equals.
new words in your collection
- search
- flag
This lesson isn’t saved. A free account remembers every lesson you finish.