The Planet enum example


/ Published in: Java
Save to your folder(s)

An example to make myself remember how powerful Java enums are!


Copy this code and paste it in your HTML
  1. public enum Planet {
  2. MERCURY (3.303e+23, 2.4397e6),
  3. VENUS (4.869e+24, 6.0518e6),
  4. EARTH (5.976e+24, 6.37814e6),
  5. MARS (6.421e+23, 3.3972e6),
  6. JUPITER (1.9e+27, 7.1492e7),
  7. SATURN (5.688e+26, 6.0268e7),
  8. URANUS (8.686e+25, 2.5559e7),
  9. NEPTUNE (1.024e+26, 2.4746e7),
  10. PLUTO (1.27e+22, 1.137e6);
  11.  
  12. private final double mass; // in kilograms
  13. private final double radius; // in meters
  14. Planet(double mass, double radius) {
  15. this.mass = mass;
  16. this.radius = radius;
  17. }
  18. public double mass() { return mass; }
  19. public double radius() { return radius; }
  20.  
  21. // universal gravitational constant (m3 kg-1 s-2)
  22. public static final double G = 6.67300E-11;
  23.  
  24. public double surfaceGravity() {
  25. return G * mass / (radius * radius);
  26. }
  27. public double surfaceWeight(double otherMass) {
  28. return otherMass * surfaceGravity();
  29. }
  30. }
  31.  
  32. // Example usage (slight modification of Sun's example):
  33. public static void main(String[] args) {
  34. Planet pEarth = Planet.EARTH;
  35. double earthRadius = pEarth.radius(); // Just threw it in to show usage
  36.  
  37. // Argument passed in is earth Weight. Calculate weight on each planet:
  38. double earthWeight = Double.parseDouble(args[0]);
  39. double mass = earthWeight/pEarth.surfaceGravity();
  40. for (Planet p : Planet.values())
  41. System.out.printf("Your weight on %s is %f%n",
  42. p, p.surfaceWeight(mass));
  43. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.