2.5 枚举类型
枚举类型是一种特殊的数据类型,该类型的变量是一组预定义的常量。变量必须等于已预先定义的值之一。常见的例子包括方向(NORTH、SOUTH、EAST和WEST)和星期几等。枚举类型使用关键字enum来定义。下面是一个星期几的枚举例子:
使用枚举类型,需要一组固定的常量。下面使用上面定义的Day枚举:
输出为:
Mondays are bad. Midweek days are so-so. Fridays are better. Weekends are best. Weekends are best.
下面是Planet示例,展示枚举值的for-each遍历:
在命令行中输入参数187时,输出如下:
$ java Planet 187 Your weight on MERCURY is 70.640674 Your weight on VENUS is 169.234832 Your weight on EARTH is 187.000000 Your weight on MARS is 70.823853 Your weight on JUPITER is 473.214257 Your weight on SATURN is 199.344906 Your weight on URANUS is 169.258786 Your weight on NEPTUNE is 212.867350