编码蝙蝠雪茄三元操作员解决方案
public boolean cigarParty(int cigars, boolean isWeekend) {
if (isWeekend == false) {
return cigars >= 40 && cigars <= 60 ? true : false;
}
if (cigars >= 40) {
return isWeekend ? true : false;
}
else {
return false;
}
}
有人对我如何对三元运营商提高效率有任何反馈吗?
public boolean cigarParty(int cigars, boolean isWeekend) {
if (isWeekend == false) {
return cigars >= 40 && cigars <= 60 ? true : false;
}
if (cigars >= 40) {
return isWeekend ? true : false;
}
else {
return false;
}
}
Does anyone have any feedback on how I could be more efficient with ternary operators?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如@codebod所说,您的大部分代码都是多余的。
这是使用三元运营商解决它的一种方法:
这是在没有三元运营商的情况下解决它的一种方法:
As @codebod said, much of your code is redundant.
This is one way to solve it with ternary operators:
This is one way to solve it without ternary operators:
这些三元运营商可以完全删除。您的每个返回语句已经评估了所需的布尔结果。与三元运营商一起编写的语句本质上说:
如果true返回true,则返回false
,这是多余的。我认为最可读的表格包括三元运营商,如果是这样,则是:
这也消除了与
40
的重复比较。These ternary operators can be removed entirely. Each of your return statements already evaluates to the required boolean result. Your statements as written with the ternary operators essentially say:
if true return true, else return false
, which is redundant.I think the most readable form that includes a ternary operator, if that's what's needed, is:
This also eliminates the repeated comparison of
cigars
with40
.您实际上根本不需要三元操作员。但是你可以这样做。
雪茄&lt; 40
,它始终是false
。true
如果后续条件中的任何一个都是正确的。我希望以下内容:
雪茄&lt; 40
它将返回false
和短路表达式。true
它将返回true
You don't really need ternary operators at all. But you can do it like so.
cigars < 40
, it is alwaysfalse
.true
if either of the subsequent conditions are true.I would prefer the following:
cigars < 40
it will returnfalse
and short circuit the expression.true
it will returntrue