`

《Thinking in Java 4th》zh_cn 练习试解

阅读更多
P107 练习21:(1)创建一个enum,它包含纸币中最小面值的6种类型。通过values()循环并打印每一个值及其ordinal()。
//: initialization/MoneyType.java

public enum MoneyType {
  ONE_FEN,FIVE_FEN,ONE_JIAO,FIVE_JIAO,ONE_YUAN,FIVE_YUAN
}
//: initialization/SimpleEnumTest.java

public class SimpleEnumTest {
  public static void main(String[] args) {
    for(MoneyType m : MoneyType.values())
      System.out.println(m + ", ordinal " + m.ordinal());
  }
} /* Output:
ONE_FEN, ordinal 0
FIVE_FEN, ordinal 1
ONE_JIAO, ordinal 2
FIVE_JIAO, ordinal 3
ONE_YUAN, ordianl 4
FIVE_YUAN, ordianl 5
*/

P107 练习22:(2)在前面的例子中,为enum写一个switch语句,对于每一个case,输出该特定货币的描述。
//: initialization/ShowMoneyType.java

public class Show {
  MoneyType type;
  public Show(MoneyType type) { this.type = type};
  public void describe() {
    System.out.print("The describe of money-type :");
    switch(type) {
      case ONE_FEN:   System.out.println("ONE FEN is the mini type.");
                      break;
      case FIVE_FEN:  System.out.println("FIVE FEN is larger than ONE FEN.");
                      break;
      case ONE_JIAO:  Syetem.out.println("ONE JIAO is 10 times larger than ONE FEN.");
                      break;
      case FIVE_JIAO: Syetem.out.println("FIVE JIAO is larger than ONE JIAO");
                      break;
      ......
    }
  }
  public static void main(String[] args) {
    Show show1 = new Show(MoneyType.ONE_FEN);
    show1.describe();
    ......
  }
}/* Output:
ONE FEN is the mini type.
......
*/
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics