Введение в программирование
Перечисления
public final static int NEW = 1; public final static int RUNNING = 2; public final static int BLOCKED = 3; public final static int FINISHED = 4;
public enum State { NEW, RUNNING, BLOCKED, FINISHED }
public /*final*/ enum Unit { KILOMETER(1e3), METER(1), MILLIMETER(1e-3); private final double length; /*private*/ Unit(double length) { this.length = length; } public double getLength() { return length; } }
public enum Operation { ADD { double eval(double x, double y) { return x + y; } }, SUBTRACT { double eval(double x, double y) { return x - y; } }, MULTIPLY { double eval(double x, double y) { return x * y; } }, DIVIDE { double eval(double x, double y) { return x / y; } }; abstract double eval(double x, double y); }
static double apply( Operation op, double x, double y ) { return op.eval(x, y); }
for (Unit u1 : Unit.values()) { for (Unit u2 : Unit.values()) { System.out.println(String.format( "There are %.1g %sS in one %s", u2.getLength()/u1.getLength(), u1, u2 )); } }
There are 1.0 KILOMETERS in one KILOMETER There are 0.0010 KILOMETERS in one METER There are 1.0e-06 KILOMETERS in one MILLIMETER There are 1.0e+03 METERS in one KILOMETER There are 1.0 METERS in one METER There are 0.0010 METERS in one MILLIMETER There are 1.0e+06 MILLIMETERS in one KILOMETER There are 1.0e+03 MILLIMETERS in one METER There are 1.0 MILLIMETERS in one MILLIMETER
Unit u = … switch (u) { case KILOMETER: return "км"; case METER: return "м"; case MILLIMETER: return "мм"; }