繁体   English   中英

如何在这种情况下编写equals()方法?

[英]How do I write the equals() method in this context?

我需要编写一个Temperature.equals()方法,将括号中的第一个温度与第二个温度进行比较,但是我不知道正确的语法。

第1部分:

public Temperature(double degreesd, char typec)
{
   degrees = degreesd;
   type = typec;
}

public void set(double degreesd, char typec)
{
   degrees = degreesd;
   type = typec;
}

第2部分:

t1.set(100, 'C');
t2.set(212, 'F');
System.out.println(t1.equals(t2));

我需要完成的equals()方法:

public boolean equals(Temperature t2)
{
   return ( Temperature.getC() == t2.getC() );
   // getC() is a function that returns degrees in Celsius as a double.
}

我不知道将t1传递到“ Temperature.getC()”所在位置的正确语法。 任何帮助表示赞赏。

public boolean equals(Temperature t2)
{
   return (this.getC() == t2.getC());
   // getC() is a function that returns degrees in Celsius as a double.
}

使用this来引用调用equals的对象。 对于t1.equals(t2)this将是t1

使用getC()方法更容易,然后您就不必像我一样遇到麻烦了:

public boolean equals(Temperature t1) {
    return this.getC() == t1.getC();
}

至于euqals方法(不使用getC() ):

public boolean equals(Temperature t1) {
    if (this.typec == t1.typec) {
        return (this.degrees == t1.degrees);
    } else {
        double fah = t1.typec == 'F' ? t1.degrees : t2.degrees;
        double cel = t1.typec == 'C' ? t1.degrees : t2.degrees;
        fah = (fah - 32) * 5 / 9;
        return fah == cel;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM