繁体   English   中英

为什么当条件= false时while循环不退出

[英]Why is while loop not exiting when conditions = false

我有一个循环正在运行,当它到达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);
            }
        }   
    }
}

感谢您提前提出任何建议。

while (power = true) 

始终为 true因为您正在分配而不是进行比较。

写:

while(power) 

代替。


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

这就是为什么我们不喜欢在比较boolean s时使用==的原因,它可能会导致这种错误。 您可以简单地编写if(someBoolean)而不是if(someBoolean == true)

while (power = true)在这里,您正在使用分配运算符并再次分配power = true 使用while(power)

暂无
暂无

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

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