修改RationalNumber类,使其实现Comparable接口。为了实现比较,首先计算两个RationalNumber对象(分子和分母)的浮点数值,然后以0.0001为误差精度进行比较。编写一个main驱动方法,测试你的修改结果。
时间: 2024-02-06 14:10:17 浏览: 91
下面是修改后的RationalNumber类实现Comparable接口的代码:
```java
public class RationalNumber implements Comparable<RationalNumber> {
private int numerator;
private int denominator;
// 构造方法
public RationalNumber(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
simplify();
}
// 获取分子
public int getNumerator() {
return numerator;
}
// 获取分母
public int getDenominator() {
return denominator;
}
// 约分
private void simplify() {
int gcd = gcd(numerator, denominator);
numerator /= gcd;
denominator /= gcd;
}
// 求最大公约数
private int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
// 重写equals方法
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof RationalNumber)) {
return false;
}
RationalNumber other = (RationalNumber) obj;
return numerator == other.numerator && denominator == other.denominator;
}
// 重写hashCode方法
@Override
public int hashCode() {
return Objects.hash(numerator, denominator);
}
// 重写toString方法
@Override
public String toString() {
return numerator + "/" + denominator;
}
// 实现Comparable接口的compareTo方法
@Override
public int compareTo(RationalNumber other) {
double thisValue = (double) numerator / denominator;
double otherValue = (double) other.numerator / other.denominator;
if (Math.abs(thisValue - otherValue) < 0.0001) {
return 0;
} else if (thisValue < otherValue) {
return -1;
} else {
return 1;
}
}
}
```
下面是测试代码:
```java
public class Test {
public static void main(String[] args) {
RationalNumber r1 = new RationalNumber(1, 2);
RationalNumber r2 = new RationalNumber(3, 4);
RationalNumber r3 = new RationalNumber(2, 4);
RationalNumber r4 = new RationalNumber(1, 3);
System.out.println("r1: " + r1);
System.out.println("r2: " + r2);
System.out.println("r3: " + r3);
System.out.println("r4: " + r4);
System.out.println("r1.compareTo(r2): " + r1.compareTo(r2));
System.out.println("r1.compareTo(r3): " + r1.compareTo(r3));
System.out.println("r1.compareTo(r4): " + r1.compareTo(r4));
}
}
```
输出结果:
```
r1: 1/2
r2: 3/4
r3: 1/2
r4: 1/3
r1.compareTo(r2): -1
r1.compareTo(r3): 0
r1.compareTo(r4): 1
```
可以看到,经过修改后,RationalNumber类实现了Comparable接口,并且可以通过compareTo方法进行比较。在测试代码中,我们创建了四个RationalNumber对象,分别比较了它们之间的大小关系,得到了正确的结果。
阅读全文