tags:

views:

362

answers:

5

Hi,

I am trying to write a method that when invoked, changes a boolean variable to true, and when invoked again, changes the same variable to false, etc.

For example: call method -> boolean = true -> call method -> boolean = false -> call method -> boolean = true

So basically,

if (a = false) { a = true; }
if (a = true) { a = false; }

I am not sure how to accomplish this, because every time I call the method, the boolean value changes to true and then false again.

Thanks.

+8  A: 

Just toggle each time it is called

public class A

  public A() {
    this.boolValue = false;
  }

  public void toggle() {
    this.boolValue = !this.boolValue;
  }
}
Randy Simon
A: 
private boolean negate(boolean val) {
    return !val;
}

I think that is what you are asking for??

rayd09
+1  A: 

Without lookin at it, set it to not itself. I don't know how to write it in Java, but in Objective-C I would say

booleanVariable = !booleanVariable;

this flips the variable.

JoePasq
+3  A: 

Assuming your code above is the actual code, you have two problems:

1) your if statements need to be '==', not '='. You want to do comparison, not assignment.

2) The second if should be an 'else if'. Otherwise when it's false, you will set it to true, then the second if will be evaluated, and you'll set it back to false, as you describe

if (a == false) {
  a = true;
} else if (a == true) {
  a = false;
}

Another thing that would make it even simpler is the '!' operator:

a = !a;

will switch the value of a.

bobDevil
The second if, if (a==true) isn't even necessary, just else suffices, unless it's a Boolean which might have a null value.
extraneon
True, but I always prefer to err on the side of being explicit in my intent, especially when answering questions such as these.
bobDevil
+2  A: 
value ^= true;

That is value xor-equals true, which will flip it every time, and without any branching or temporary variables.

ILMTitan
This is fabulous, thanks :)
aperson