← Java from Scratch
Lesson 46 of 88 · 10 XP
Enumerations (enum)
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
enum is a fixed set of named values. In Java it's a full-fledged class: the values can have
fields, a constructor and methods.
enum Planet {
MERCURY(3.7), EARTH(9.8), JUPITER(24.8); // constructor calls
private final double gravity;
Planet(double g) { gravity = g; }
double weight(double mass) { return mass * gravity; }
}
Planet p = Planet.valueOf("EARTH");
p.name() // "EARTH"
p.ordinal() // 1 — the number in order
Planet.values() // all the values as an array
switch (p) {
case EARTH -> System.out.println("home");
default -> System.out.println("far away");
}
Task. Finish enum Direction (NORTH, EAST, SOUTH, WEST) with the fields dx, dy and the methods right()
and left() (the next/previous one in a circle, using values() and ordinal()). A robot at (0, 0) faces NORTH;
the commands L R F come on one line. Print x y DIRECTION.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.