《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.
......
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值