java · level 2 · unit 4 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
An lists every choice a value can take.
A coffee comes small, medium or large. Store the size as text and someone will type "meduim". An enum fixes the choices: enum Size { SMALL, MEDIUM, LARGE }. Now a Size box can only hold one of those three.
Write a choice with the enum's name and a dot: Size.LARGE. A typo like Size.LRAGE is caught before anything runs. Compare choices with ==, which is safe here because each choice exists only once.
gives every choice in order, ready for a for-each loop, and .name() gives a choice's name as text.
public class Main {
enum Size { SMALL, MEDIUM, LARGE }
public static void main(String[] args) {
Size order = Size.MEDIUM;
if (order == Size.LARGE) {
System.out.println("That is a big one!");
} else {
System.out.println("You chose " + order);
}
for (Size size : Size.values()) {
System.out.println(size.name().toLowerCase());
}
}
} Enum choices are written in capitals, like constants, because they never change.
guess first
What do the traffic lights say?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
enum Light { RED, AMBER, GREEN }
static String advice(Light light) {
if (light == Light.GREEN) {
return "Go";
} else if (light == Light.AMBER) {
return "Get ready";
}
return "Stop";
}
public static void main(String[] args) {
Light now = Light.AMBER;
System.out.println(now + ": " + advice(now));
System.out.println(Light.values().length + " lights");
}
}
your turn
Your turn. Pick a day off.
Choose a day on line 4, written as Day. followed by one of the seven names. Then press run to see whether it is the weekend.
output
press run to see what happens
fix it
A typo crept into the order. Fix it!
output
press run to see what happens
- Java says
cannot find symbolon line 4. Compare the choice there with the list on line 2. - Two letters in
MEDUIMare swapped. The enum only knowsMEDIUM. - Change
Size.MEDUIMtoSize.MEDIUMon line 4, then press run.
nailed it
you locked the choices in place. :D
- An enum lists every choice a value can take.
- Compare enum choices with
==. values()gives every choice, in order.
new words in your collection
- enum
- values()
This lesson isn’t saved. A free account remembers every lesson you finish.