gpt4 book ai didi

java - 冗余 If 消息

转载 作者:行者123 更新时间:2023-11-29 10:12:12 31 4
gpt4 key购买 nike

我的 Fraction 程序运行流畅,但 NetBeans IDE 告诉我以下 if 是多余的:

public boolean equals(Object other)
{
Fraction bool = (Fraction) other;

if(this.numerator == bool.numerator && this.denominator == bool.denominator)
{
return true;
}
else return false;
}

上面的代码完美地编译/运行并通过了所有测试用例,但是 NetBeans 的冗余标志真的让我很困扰。我将 reduceToLowestTerms() 添加到我的代码中,标志消失了,但我的构造函数中已经有了 reduceToLowestTerms()。这是非冗余代码(根据 NetBeans )的样子:

public boolean equals(Object other)
{
Fraction bool = (Fraction) other;

if(this.numerator == bool.numerator && this.denominator == bool.denominator)
{
bool.reduceToLowestTerms();
this.reduceToLowestTerms();
return true;
}
else return false;
}

如有任何建议,我们将不胜感激

最佳答案

这看起来类似于我的 IDE 对此语句发出的警告:

'if' statement can be simplified

if(foo())
{
return true;
}
else
{
return false;
}

can be simplified to

return foo();

这只是过于复杂和冗长的代码。您的简化是:

return this.numerator == bool.numerator && this.denominator == bool.denominator;

但是正如您所注意到的,您的代码已经是正确的。这个改动不是必须的,但是会让代码更简洁,更简单。

添加对另一个方法 (reduceToLowestTerms()) 的调用会移除此“标志”的原因是代码无法再以这种方式简化为单个返回声明。

关于java - 冗余 If 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28821081/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com