如果不为 true 则重新分配布尔值
我有一个方法 foo() 和 foobar() 都返回一个布尔值。无论结果如何,都必须执行它们中的每一个。
boolean changed = true;
while(changed) {
changed = foo();
if(!changed) {
changed = foobar();
}
else {
foobar();
}
}
我希望只要更改为真,循环就继续执行,但我觉得 foobar() 的 ifs 和 elses 的第二个代码块不是很...优雅。是否有更好的方法来编写该部分,以便更改的变量只有在尚未为真时才会重新分配?
谢谢!
I have a method foo() and foobar() that both return a boolean. Each of them must be executed regardless of the result.
boolean changed = true;
while(changed) {
changed = foo();
if(!changed) {
changed = foobar();
}
else {
foobar();
}
}
I want the loop to keep executing for as long as changed is true, but I feel like the second code block of ifs and elses for foobar() is not very... elegant. Is there a better way to write that part so that the variable changed will only be reassigned if it's not already true?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
怎么样:
注意按位或运算符的使用。
How about:
Note the use of the bitwise or operator.
只要更改为真,我希望循环继续执行
是什么意思?
如果两个方法都返回 false,你想停止循环吗
如果是,则执行:
I want the loop to keep executing for as long as changed is true
means?
do u want to stop loop if both method returns false
if yes then do:
除了按位或选项之外,您还可以确保将
changed
放在表达式中的第二个位置,并且所有方法都将被执行:我更喜欢按位选项,因为它表明这些方法具有必要的副作用。上述内容应该有详细的记录,以防止有人稍后出现并“修复它以提高性能”。
Besides the bitwise OR option, you can also just make sure you put
changed
second in the expression and all the methods will be executed:I like the bitwise option better since it communicates that the methods have necessary side effects. The above should be well documented to prevent somebody from coming along later and "fixing it to be more performant."
基本上,只要 foo() 或 foobar() 之一返回 true,您就希望继续执行循环。
您可以通过使用语法上等效的代码结构来缩短此长度:
最终的简写:
Basically you want, so long as one of foo() or foobar() return true, to continue executing the loop.
You can shorten this by using syntactically equivalent code structures:
To the ultimate short-hand:
您可以使用下面
我编辑的答案的缩短代码语法。感谢大家指出错误:)
You can use below shortened code styntax
I edited the answer. Thanks all for pointing out the error :)
使用 do-while 的一个很好的例子:
a nice case for using the do-while: