当condition = false时,为什么while循环不会退出

时间:2014-10-28 07:35:37

标签: java while-loop

我有一个循环运行,当它到达else语句时,它应该停止运行。当我调试布尔功率确实更新但它仍然进入循环。我知道我可以使用System.Exit(0);或休息;但我会理解为什么它会继续运行错误的条件背后的逻辑?

public class Mmu {      
    //code omitted
    public static final Mmu MMU = new Mmu();

    public static void main(String[] args) {
        MMU.runProcesses();
        //code omitted
    }
        private Mmu() {
            //code omitted 
        }
    protected void runProcesses(){
        boolean power= false; // running processes,  normally this would start as false but I changed to test
        boolean twoFinished = false;
        boolean oneFinished = false;
        while (power = true) { //still entering this when power = false why
            twoFinished = MMU.processTwo.finished();
            oneFinished = MMU.processOne.finished();
            if (oneFinished = false) {
                MMU.processOne.thread();
            } else if (twoFinished = false) {
                MMU.processTwo.thread();
            } else {
                power = false;
                System.out.println("All processes Finished");
                //System.exit(0);
            }
        }   
    }
}

感谢您提前获得任何建议。

2 个答案:

答案 0 :(得分:10)

while (power = true) 

总是 true,因为您正在分配而不是比较。

写:

while(power) 

代替。


分配的表达式返回分配的值。

这就是为什么我们在比较==时不想使用boolean,这可能会导致这种错误。您只需撰写if(someBoolean)而不是if(someBoolean == true)

答案 1 :(得分:5)

while (power = true)此处您正在使用分配运算符并再次分配power = true。使用while(power)

相关问题