2)定义钱类,包括元角分信息,提供构造方法、钱加减方法、钱翻倍方法、钱比较大小的方法、格式化显示钱的方法。
时间: 2024-10-21 14:06:47 浏览: 18
在Java中,我们可以创建一个名为`Money`的类来表示金额,包含元(yuan)、角(jiao)和分(fen)的信息。这个类可以有以下几个关键方法:
1. **构造方法**(Constructor):
```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 = jiao;
this.fen = fen;
}
}
```
2. **加减方法** (`add`, `subtract`):
```java
public Money add(Money other) {
Money result = new Money(this.yuan + other.yuan, this.jiao + other.jiao, this.fen + other.fen);
return result;
}
public Money subtract(Money other) {
Money result = new Money(this.yuan - other.yuan, Math.min(this.jiao - other.jiao, 99), this.fen - other.fen);
// 确保结果的角不超过99
return result;
}
```
3. **翻倍方法** (`doubleAmount`):
```java
public Money doubleAmount() {
return new Money(this.yuan * 2, this.jiao * 2, this.fen * 2);
}
```
4. **比较大小方法** (`compareTo` 或 `equals`):
```java
@Override
public int compareTo(Money other) {
int totalComparison = Integer.compare(this.getTotalValue(), other.getTotalValue());
if (totalComparison == 0) return 0; // 如果相等则返回0
return totalComparison > 0 ? 1 : -1;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Money money = (Money) obj;
return yuan == money.yuan && jiao == money.jiao && fen == money.fen;
}
```
5. **格式化显示方法** (`toString`):
```java
@Override
public String toString() {
return yuan + "元" + jiao + "角" + fen + "分";
}
```
阅读全文