简体   繁体   English

我怎样才能简化这个 if 语句?

[英]How can I simplify this if statement?

Basically, I am doing a java program for school.基本上,我正在为学校做一个java程序。 The checkstyle program we are required to use is saying that I am not simplifying my if statement enough.我们需要使用的 checkstyle 程序表明我没有充分简化 if 语句。 Is there a better way to do this?有一个更好的方法吗?

My code:我的代码:

    if (check() == true)
    {
        return amount * 0.85;
    }
    else
    {
        return amount;
    }

No need to add == true when you're already working with a boolean当您已经在使用布尔值时,无需添加== true

if (check()) {
...
}
else {
...
}

您可以使用三元运算符。

return check() ? amount * 0.85 : amount

Convert the boolean to an integer, then use that as an index int an array to get the value to multiply amount by, and you don't need an if or ternary operator:将布尔值转换为整数,然后将其用作数组的索引 int 以获取要乘以amount的值,并且您不需要if或三元运算符:

return amount * (new double[] {1.0, 0.85}[Boolean.compare(check(), false)]);

I am kidding, don't downvote me please.我在开玩笑,请不要贬低我。 This is the worst way I could come up with.这是我能想到的最糟糕的方法。

In seriousness, style checking programs mostly care about how complex your expressions are and how many potential branches there are (cyclomatic complexity), so remove the else , and don't compare true to true to get true , and that should be enough to make it happy.严肃地说,样式检查程序主要关心你的表达式有多复杂以及有多少潜在的分支(圈复杂度),所以删除else ,不要比较truetrue以获得true ,这应该足以使它快乐。

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

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