package 枚举; //将方法附加到枚举常量 public class UnitsConverter { private static double numberToConvert = 0; public static void main(String[] args) { // TODO Auto-generated method stub if(args.length == 0) { System.out.println("Usage:java UnitsConverter<weight in pounds>"); System.exit(0); } numberToConvert = Double.parseDouble(args[0]); System.out.println("lbs "+args[0]+" equals:\n"); //遍历Converter枚举的所有元素 for(Converter conv:Converter.values()) { System.out.printf("%s:%f%n",conv,conv.performConversion(numberToConvert)); } } } //枚举Converter:变换器 //Converter中的每个常量都需要实现这个方法。 enum Converter { //把磅换算成千克,需要把指定值乘以常量0.45359237 KG("KG"){ double performConversion(double f){ return f*=0.45359237; } }, //把磅换算成克拉 CARAT("carat"){ double performConversion(double f){ return f*=2267.96185; } }, // GMS("gms"){ double performConversion(double f){ return f*=453.59237; } }, // OUNCE("ounce"){ double performConversion(double f){ return f*=16; } }, // STONE("stone"){ double performConversion(double f){ return f*=0.071428571429; } }; private final String symbol; //构造方法 Converter(String symbol) { this.symbol=symbol; } @Override public String toString() { return symbol; } //定义的抽象方法performConversion:执行转换 abstract double performConversion(double f); }
lbs 5.0 equals: KG:2.267962 carat:11339.809250 gms:2267.961850 ounce:80.000000 stone:0.357143
原文地址:http://blog.csdn.net/u012110719/article/details/41018955