定义钱类,包括元角分信息,提供构造方法、钱加减方法、钱翻倍方法、钱比较大小的方法、格式化显示钱的方法。
时间: 2024-10-21 13:01:21 浏览: 19
定义一个表示钱的类,通常命名为`Money`,可以按照以下方式设计:
```java
public class Money {
private int yuan; // 元
private int jiao; // 角
private int fen; // 分
// 构造方法
public Money(int yuan, int jiao, int fen) {
this.yuan = yuan;
this.jiao = Math.min(100, jiao); // 角数限制在0-100之间
this.fen = Math.min(1000, fen); // 分数限制在0-1000之间
}
// 钱加减方法
public Money add(Money other) {
int totalYuan = this.yuan + other.yuan;
int totalJiao = this.jiao + other.jiao;
int totalFen = this.fen + other.fen;
return new Money(totalYuan, totalJiao, totalFen);
}
public Money subtract(Money other) {
if (this.value() >= other.value()) {
int differenceYuan = this.yuan - other.yuan;
int differenceFen = this.fen - other.fen;
return new Money(differenceYuan, differenceJiaoFromFen(differenceFen), 0);
} else {
throw new IllegalArgumentException("不能从更小的钱中减去更多");
}
}
// 钱翻倍方法
public Money doubleValue() {
return new Money(this.yuan * 2, this.jiao * 2, this.fen * 2);
}
// 比较大小的方法
@Override
public boolean equals(Object obj) {
if (obj instanceof Money) {
Money other = (Money) obj;
return this.yuan == other.yuan && this.jiao == other.jiao && this.fen == other.fen;
}
return false;
}
@Override
public int compareTo(Money other) {
int yuanDiff = this.yuan - other.yuan;
if (yuanDiff != 0) return yuanDiff;
return Integer.compare(this.jiao + this.fen / 10, other.jiao + other.fen / 10);
}
// 格式化显示钱的方法
@Override
public String toString() {
return String.format("%d元%d角%d分", yuan, jiao, fen);
}
// 私有方法转换角和分
private int differenceJiaoFromFen(int differenceFen) {
differenceFen %= 100; // 取余得到角数
return Math.max(0, differenceFen / 10); // 向上取整到角
}
// 返回总值用于判断是否能减法运算
private int value() {
return yuan * 100 + jiao * 10 + fen;
}
}
```
阅读全文