10. Create an enum of the least-valuable six types of paper currency. Loop through the values( ) and print each value and its ordinal( ).
时间: 2024-10-23 07:15:54 浏览: 21
首先,我们创建一个枚举(enum)类型,代表最不值钱的六种纸币类型。在Java中,枚举是一种特殊的类,它可以包含常量和方法。然后我们可以使用`values()`方法获取枚举的所有实例,并通过循环打印它们的名称和对应的序号(ordinal)。
```java
public enum CurrencyValue {
DOLLAR("$1", 0),
QUARTER("$0.25", 1),
NICKEL("$0.05", 2),
PENNY("$0.01", 3),
HALF_DOLLAR("$0.50", 4),
ONE_CENT("1 cent", 5); // 尽管1 cent的实际价值非常小,但我们仍将其视为一种货币
private final String denomination;
private final int ordinal;
CurrencyValue(String denomination, int ordinal) {
this.denomination = denomination;
this.ordinal = ordinal;
}
public String getDenomination() {
return denomination;
}
public int getOrder() {
return ordinal;
}
public static void printValues() {
for (CurrencyValue currency : CurrencyValue.values()) {
System.out.println("Value: " + currency.getDenomination() + ", Ordinal: " + currency.getOrder());
}
}
}
// 调用printValues()方法来显示所有枚举值
CurrencyValue.printValues();
```
当你运行这段代码,它会输出每种纸币类型及其对应的序号:
```
Value: $1, Ordinal: 0
Value: $0.25, Ordinal: 1
Value: $0.05, Ordinal: 2
Value: $0.01, Ordinal: 3
Value: $0.50, Ordinal: 4
Value: 1 cent, Ordinal: 5
阅读全文