[英]Why is while loop not exiting when conditions = false
I've got a loop running and when it reaches the the else statement it should stop running. 我有一个循环正在运行,当它到达else语句时,它应该停止运行。 When I debug the boolean power does update but it still enters the loop. 当我调试时,布尔电源会更新,但仍会进入循环。 I know I could use System.Exit(0); 我知道我可以使用System.Exit(0); or a break; 或休息; but I would understand the logic behind why it would keep running with false conditions? 但是我会理解为什么它会继续在错误条件下运行的逻辑?
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);
}
}
}
}
Thanks for any advice in advance. 感谢您提前提出任何建议。
while (power = true)
Is always true
since you're assigning and not comparing. 始终为 true
因为您正在分配而不是进行比较。
Write: 写:
while(power)
instead. 代替。
The expression of the assignment returns the assigned value. 分配的表达式返回分配的值。
That's why we don't like to use ==
when we compare boolean
s, it might lead to this kind of mistakes. 这就是为什么我们不喜欢在比较boolean
s时使用==
的原因,它可能会导致这种错误。 You can simply write if(someBoolean)
instead of if(someBoolean == true)
. 您可以简单地编写if(someBoolean)
而不是if(someBoolean == true)
。
while (power = true)
here your are using assigning operator and assigning power = true
again. while (power = true)
在这里,您正在使用分配运算符并再次分配power = true
。 Use while(power)
使用while(power)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.