×

java · level 2 · unit 4 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.