I've got a loop running and when it reaches the the else statement it should stop running. When I debug the boolean power does update but it still enters the loop. I know I could use 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.
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. You can simply write if(someBoolean)
instead of if(someBoolean == true)
.
while (power = true)
here your are using assigning operator and assigning power = true
again. Use while(power)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.