我目前正在做一个项目,我需要比较两个分数。我以前没有做过这样的事情,覆盖了一个方法,所以我需要一点帮助。
这就是困扰我的事情;
所以我有一个叫做分数的类,在这个类中,我有两个字段。
public class Fraction {
private int denominator;
private int numerator;
public Fraction(int numerator, int denominator) {
//Throwing an error if the denominator is 0.
if (denominator == 0) {
throw new IllegalArgumentException("Denominator cannot be zero!");
}
//When both numbers are negative
if (denominator < 0 && numerator < 0) {
denominator *= -1;
numerator *= -1;
}
//When the numerator is negative
if (denominator < 0 && numerator > 0) {
denominator *= -1;
numerator *= -1;
}
this.denominator = denominator;
this.numerator = numerator;
}
public Fraction(int numerator) {
this.numerator = numerator;
this.denominator = 1;
}
public Fraction() {
this.numerator = 0;
this.denominator = 1;
}我还有其他一些有用的方法来比较像这样的两个分数:
//converts the current fraction to the lowest terms
public void toLowestTerms() {
int reminder = 0, gcd = 0;
int up = numerator, bottom = denominator;
while (up != 0 && bottom != 0) {
reminder = up % bottom;
up = bottom;
bottom = reminder;
gcd = up;
}
numerator /= gcd;
denominator /= gcd;
}所以这就是我被卡住的部分。
@Override
//must take in an "Object" to properly override the Object class's equals method, but should ultimately check if two fractions are equal
public boolean equals(Object obj) {
// If the object is compared with itself then return true
if(obj == this){
return true;
}
/* check if o is an instance of Complex or not
"null instanceof [type]" also returns false */
if (!(obj instanceof Fraction)) {
return false;
}
//This object is created for
Fraction compareObject = new Fraction(this.getNumerator(), this.getDenominator());
compareObject.toLowestTerms();
// typecast o to Fraction so that we can compare data members
Fraction x = (Fraction) obj;
//converting to the lowest terms to compare
((Fraction) obj).toLowestTerms();
// Compare the data members and return accordingly
return (compareObject.getNumerator()== x.getNumerator() && compareObject.getDenominator() == x.getDenominator());
}这是正确的做法,还是有一种方法可以正确地做到这一点?从技术上讲,我正在创建一个使用toLowestTerms方法的对象。因为当我想要比较,例如,1/2 == 12/24时,我需要减少分子和分母,才能做好检查。
'Fraction compareObject = new Fraction(this.getNumerator(), this.getDenominator());
compareObject.toLowestTerms();` 发布于 2020-02-01 21:49:16
你的代码在我看来很好,我想它会工作的。我想补充几点,主要是关于你的评论:
1.
如果对象与自身进行比较,则返回true
如果对象相同(即相同的实例)
2.
Complex的
实例
你是说instance of Fraction
toLowestTerms改变了当前的实例this。出于这个原因,您创建了一个名为compareObject的新实例来表示this,我只能假设这样您就不会在调用compare时更改this (这是件好事!)但是对于参数obj,您正在更改实例!你没有复制一份。您也可以通过制作副本来解决这个问题,但是我建议您的toLowestTerms方法返回一个新的Fraction副本,其中包含最少的条目。然后,您可以在this和obj上安全地调用它,获取新的副本,并对两者进行比较。toLowestTerms。因此,不可能有一个不是最低条款的Fraction。这将极大地简化equals、hashCode等方法。但这是你需要做出的更深层次的设计决定。如果这样做,您可以查看一个名为Lombok的库,它将根据类的属性为您生成equals和hashCode!但不会像toLowestTerms.那样做进一步的计算
https://stackoverflow.com/questions/60017418
复制相似问题