How do you put an if...else statement within a for statement?
This is the code:
// This is within a actionListener. When ever I press a button, this happens.
for (int i = 0; i < booleanVariable.length; i++) {
//length is 8
System.out.println("booleanVariable is" + booelanVariable[i]);
if (booleanVariable[i] = true) {
booleanVariable[i] = false;
System.out.println("booleanVariable was true")
break;
} else {
System.out.println(" booleanVariable is false");
}
}
This is the output over 3 presses:
booleanVariable is true
booleanVariable was true
//correct
booleanVariable is false
booleanVariable was true
//incorrect.
booleanVariable is false
booleanVariable was true
//incorrect
This means that, for some reason, even if booleanVariable is false, the output says is true, which is false.
What I’ve found:
- Without the
break;statement, the program goes around the for all 8 times and outputs exactly the same as without abreak, only incorrect values another 5 times.
What I’ve tried:
- Changing the if from true to false (out of desperation)
- If within a While within a For
- else, else if
- case switch
Normally, I’d just use a switch, but I’m using booleans, and booleans dont work is switches.
If someone knows the answer, I’d be forever grateful. Thanks.
Change your
to
You need to use
==operator for comparison. One=sets the value totruewhich returns always true.You can also change it to