如果不是真,则重新分配布尔值

时间:2011-03-14 05:00:51

标签: java boolean-logic boolean-operations

我有一个方法foo()和foobar()都返回一个布尔值。无论结果如何,都必须执行它们。

boolean changed = true;
while(changed) {
    changed = foo();
    if(!changed) {
        changed = foobar();
    }
    else {
        foobar();
    }
}

我希望循环继续执行,只要change为true,但我觉得foobar()的ifs和elses的第二个代码块不是很优雅。是否有更好的方法来编写该部分,以便更改的变量只有在不是真的时才会被重新分配?

谢谢!

6 个答案:

答案 0 :(得分:3)

怎么样:

changed = foo() | foobar();

请注意使用按位或运算符。

答案 1 :(得分:3)

我希望循环在更改为真时继续执行
意味着什么? 如果两个方法都返回false,你想停止循环吗? 如果是,则执行:

boolean changed = true;
boolean changed1 = true;

    while(changed || changed1) {
        changed = foo();
        changed1 = foobar();
    }

答案 2 :(得分:1)

除了按位OR选项之外,您还可以确保在表达式中放置changed秒,并且将执行所有方法:

changed = foo();
changed = bar() || changed;
changed = baz() || changed;

我更喜欢按位选项,因为它表示方法有必要的副作用。上面应该有很好的记录,以防止有人后来出现并“修复它以提高性能。”

答案 3 :(得分:0)

您可以使用以下缩短的代码styntax

boolean changed = true;
while(changed) {
    changed = (foo())?foobar():(true|foobar());
}

我编辑了答案。感谢大家指出错误:)

答案 4 :(得分:0)

基本上你想要的,只要foo()或foobar()中的一个返回true,就可以继续执行循环。

boolean time_to_stop = false;
while (!time_to_stop) {
    boolean foo_result = foo();
    boolean foobar_result = foobar();
    if (false == (foo_result || foobar_result) ) {
        time_to_stop = true;
    }
}

您可以通过使用语法上等效的代码结构来缩短它:

boolean keep_going = true;
while (keep_going) {
    keep_going = foo() | foobar(); 
    // bit-wise OR, avoids compiler short-circuiting optimization
}

最终的简介:

while ( foo() | foobar() ) {};

答案 5 :(得分:0)

使用do-while的一个很好的例子:

boolean changed;    // no initial value needed
do {
    changed = foo() | foobar();  // should not be ||
} while(changed);