`

java枚举

 
阅读更多
写了一个简单的枚举类,来理解枚举的使用,有点;(计算太阳系内各个行星的表面的重力系数)

import static java.lang.System.out;

public enum PlanetEnum
{
  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 double mass;
  private double radius;

  private PlanetEnum(double mass, double radius)
  {
    this.mass = mass;
    this.radius = radius;
  }

  public double getMass()
  {
    return mass;
  }

  public double getRadius()
  {
    return radius;
  }

  public static final double G = 6.67300E-11; // 地球引力常量

  public double surfaceGravity()
  {
    return G * mass / (radius * radius);
  }
  
  public double otherSurfaceGravity(PlanetEnum otherPlanet){
    double otherGravity = otherPlanet.getMass() * surfaceGravity();
    return otherGravity;
  }

  public static void main(String[] args)
  {
    out.println(PlanetEnum.EARTH.getMass());
    out.println(PlanetEnum.EARTH.getRadius());
    
    out.println("==========================");
    PlanetEnum [] aa = PlanetEnum.values();
    double gravity = 0.0;
    for(PlanetEnum peEnum : aa){
      gravity = peEnum.otherSurfaceGravity(peEnum);
      out.println("the gravity on " + peEnum + " is " + gravity);
    }
  }
}

输出结果:
the gravity on MERCURY is 1.22310972659565E24
the gravity on VENUS is 4.319480720382284E25
the gravity on EARTH is 5.858065279418269E25
the gravity on MARS is 2.383879142609239E24
the gravity on JUPITER is 4.713173567199915E28
the gravity on SATURN is 5.943834947028425E27
the gravity on URANUS is 7.706781726348676E26
the gravity on NEPTUNE is 1.1426442037670253E27
the gravity on PLUTO is 8.325448475326993E21
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics