我非常坚持一个项目,到目前为止我已经得到了:
public class MyInt implements Comparable<MyInt> {
private int value;
MyInt(int x) {
value = x;
}
public String toString() {
return ("" + value);
}
public int intValue() {
return value;
}
public int compareTo(MyInt rhs) {
MyInt myInt = (MyInt) rhs;
int myInteger = myInt.intValue();
int result = 0;
if (value < myInteger) {
result = -1;
} else if (value == myInteger) {
result = 0;
} else {
result = +1;
}
return result;
}
}
这就是问题所在: 请考虑以下Java Library接口:
public interface Comparable<T> {
int compareTo(T rhs);
}
完成下面实现上述类的实现 接口(注意这个接口是由java自动导入的 - 不要 在你的项目中重新输入它)。 compareTo方法应返回-1 if value小于rhs.value,如果两边相等则为0,如果值为则为+1 大于rhs.value。
public class MyInt implements Comparable<MyInt> {
private int value;
MyInt(int x) {...}
public String toString() {...}
public int intValue() {...}
public int compareTo(MyInt rhs){...}
}
现在我需要在另一个使用有理数执行基本算术的类中实现类似的接口,是否最好使用继承来实现这个?类:
public class Rational {
private int num;
private int denom;
public Rational() {
this(0,1);
}
public Rational(int num, int denom) {
this.num = num;
this.denom = denom;
}
int getNum() {
return num;
}
int getDenom() {
return denom;
}
public Rational add(Rational rhs) {
return new Rational(num * rhs.denom + rhs.num * denom, denom * rhs.denom);
}
public Rational subtract(Rational rhs) {
return new Rational(num * rhs.denom - rhs.num * denom, denom * rhs.denom);
}
public Rational multiply(Rational rhs) {
return new Rational(num * rhs.num, denom * rhs.denom);
}
public Rational divide(Rational rhs) {
return new Rational(num * rhs.denom, denom * rhs.num);
}
public String toString() {
String result;
if (num == 0)
result = "0";
else if (denom == 1)
result = num + "";
else
result = num + "/" + denom;
return result;
}
public static void main(String[] args) {
Rational r1 = new Rational(1, 2); // 1/2
Rational r2 = new Rational(3, 4);// 3/4
Rational result = new Rational();
result = r1.add(r2);
System.out.println(result);
Rational result1 = new Rational();
result1 = r1.subtract(r2);
System.out.println(result1);
Rational result2 = new Rational();
result2 = r1.multiply(r2);
System.out.println(result2);
Rational result3 = new Rational();
result3 = r1.divide(r2);
System.out.println(result3);
}
}
答案 0 :(得分:1)
您需要比较this.intValue()
(当前实例)和rhs.intValue()
(“右侧”)。将rhs
与其自身进行比较(通过将其别名化为myInt
)应始终返回0.并将结果存储为临时变量似乎不会在代码中服务于任何目的。你可以做点什么
// MyInt myInt = (MyInt) rhs;
if (this.intValue() < rhs.intValue()) {
return -1;
} else if (this.intValue() == rhs.intValue()) {
return 0;
}
return 1;
答案 1 :(得分:0)
无需显式转换参数(MyInt rhs),因为您只是比较两个整数,所以使用Integer中的静态比较方法:
public int compareTo(MyInt rhs) {
return Integer.compare(this.value, rhs.intValue());
}
我建议将int字段更改为Integer以避免原语自动装箱中的性能损失