TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
java tutorial fourth edition 4.5
Enum Types Each enum constant is declared with values for the mass and radius parameters. These values are passed to the constructor when the constant is created. Java requires that the constants be defined first, prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must end with a semicolon.
Note
The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
- public enum Planet {
- MERCURY (3.303e+23, 2.4397e6),
- VENUS (4.869e+24, 6.0518e6),
- EARTH (5.976e+24, 6.37814e6),
- MARS (6.421e+23, 3.3972e6),
- JUPITER (1.9e+27, 7.1492e7),
- SATURN (5.688e+26, 6.0268e7),
- URANUS (8.686e+25, 2.5559e7),
- NEPTUNE (1.024e+26, 2.4746e7),
- PLUTO (1.27e+22, 1.137e6);}
- private final double mass; // in kilograms
- private final double radius; // in meters
- Planet(double mass, double radius) {
- this.mass = mass;
- this.radius = radius;
- }
- private double mass() { return mass; }
- private double radius() { return radius; }
-
- // universal gravitational constant (m3 kg-1 s-2)
- public static final double G = 6.67300E-11;
- double surfaceGravity() {
- return G * mass / (radius * radius);
- }
- double surfaceWeight(double otherMass) {
- return otherMass * surfaceGravity();
- }
- public static void main(String[] args) {
- double earthWeight = Double.parseDouble(args[0]);
- double mass = earthWeight/EARTH.surfaceGravity();
- for (Planet p : Planet.values())
- System.out.printf("Your weight on %s is %f%n",
- p, p.surfaceWeight(mass));
- }
- }
复制代码
If you run Planet.class from the command line with an argument of 175, you get this output:
- $ java Planet 175
- Your weight on MERCURY is 66.107583
- Your weight on VENUS is 158.374842
- Your weight on EARTH is 175.000000
- Your weight on MARS is 66.279007
- Your weight on JUPITER is 442.847567
- Your weight on SATURN is 186.552719
- Your weight on URANUS is 158.397260
- Your weight on NEPTUNE is 199.207413
- Your weight on PLUTO is 11.703031
-
复制代码
practice :
public enum FC {
BOJAN ("Bojan", 27, 1990),
SILVA ("Henry", 14, 1977),
PUYOL ("Puyol", 5, 1978),
XAVI ("Xavi", 6, 1980),
INIESTA ("Iniesta", 8, 1984),
MESSI ("Messi", 19, 1987);
private String name;
private int num;
private int year;
FC(String name, int num, int year){
this.name = name;
this.num = num;
this.year = year;
}
int getAge(){
return 2010 - year;
}
public static void main(String[] args){
for(FC fc : FC.values()){
System.out.println("Name :" + fc.name +
" Number :" + fc.num +
" Age :" + fc.getAge());
}
}
}
--------------
Name :Bojan Number :27 Age :20
Name :Henry Number :14 Age :33
Name :Puyol Number :5 Age :32
Name :Xavi Number :6 Age :30
Name :Iniesta Number :8 Age :26
Name :Messi Number :19 Age :23
源码下载:http://file.javaxxz.com/2014/10/29/235706421.zip |
|