Reputation: 805
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:
break;
statement, the program goes around the for all 8 times and outputs exactly the same as without a break
, only incorrect values another 5 times.What I've tried:
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.
Upvotes: 0
Views: 395
Reputation: 3350
You should change if (booleanVariable[i] = true) as if (booleanVariable[i] == true). need '==' instead of '='.
Upvotes: 2
Reputation: 145
There's an error in the if statement --
You are assigning true to the variable, that's why it's outputting true each time. it needs to be == (equals) not = (assign).
Upvotes: 3
Reputation: 8101
if (booleanVariable[i])
instead of if (booleanVariable[i] = true)
....=
is assignment operator...you could also use ==
instead
Upvotes: 2
Reputation: 1721
You have to use == to compare the values. Yu use the = that asigns the value true to the variable so it will always be true
if (booleanVariable[i] == true)
Upvotes: 4
Reputation: 15319
Change your
if (booleanVariable[i] = true) {
to
if (booleanVariable[i] == true) {
You need to use ==
operator for comparison. One =
sets the value to true
which returns always true.
You can also change it to
if (booleanVariable[i]) {
Upvotes: 5
Reputation: 1725
Your problem may be in this line:
if (booleanVariable[i] = true) {
Boolean comparisons should use ==
, unless you are intending to set the value to true. In any event, this line will always evaluate to true.
Note also that you never really need to compare to true
, you can simply say something like:
if (booleanVariable[i]) {
since if the value is true, the code block will be entered, and if it is false, it will proceed to the else case.
Upvotes: 5