java · level 2 · unit 4 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Each choice in an enum can carry values of its own.
An enum is a class underneath, so it can have fields, a constructor and methods. Write each choice with its values in brackets, like PENNY(1), and end the list of choices with a semicolon. The constructor then fills in each choice's field.
turns text into a choice, which is handy for typed answers. The text must match a name exactly, capitals included. Otherwise Java stops with an , its exception for a value a method cannot work with.
public class Main {
enum Coin {
PENNY(1), TWOPENCE(2), FIFTY(50), POUND(100);
private final int pence;
Coin(int pence) {
this.pence = pence;
}
int getPence() { return pence; }
}
public static void main(String[] args) {
Coin coin = Coin.valueOf("FIFTY");
System.out.println(coin + " is worth " + coin.getPence() + "p");
int total = 0;
for (Coin each : Coin.values()) {
total = total + each.getPence();
}
System.out.println("One of each: " + total + "p");
}
} Use .toUpperCase() on typed text before valueOf, so fifty works too.
guess first
Small and large cups. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
enum Size {
SMALL(250), MEDIUM(350), LARGE(500);
private final int millilitres;
Size(int millilitres) {
this.millilitres = millilitres;
}
int getMillilitres() { return millilitres; }
}
public static void main(String[] args) {
Size small = Size.SMALL;
Size large = Size.valueOf("LARGE");
System.out.println(large.getMillilitres() - small.getMillilitres() + "ml more");
}
}
your turn
Your turn. Order a drink.
Type a size between the quotes on line 11, in any capitals you like: small, medium or large. Then press run.
output
press run to see what happens
fix it
The customer typed in small letters. Fix it!
output
press run to see what happens
- Java stopped with an
IllegalArgumentExceptionon line 14. What did the customer type? - They typed medium in small letters, but the choices are named in capitals.
valueOfneeds an exact match. - Change
keyboard.nextLine()tokeyboard.nextLine().toUpperCase()on line 14, then press run.
nailed it
your choices carry their own values. :D
- Enum choices can carry values, like
PENNY(1). valueOfturns exactly matching text into a choice.- Use
.toUpperCase()on typed text beforevalueOf.
new words in your collection
- valueOf
- IllegalArgumentException
This lesson isn’t saved. A free account remembers every lesson you finish.