How to make a boolean variable switch between true and false every time a method is invoked?

后端 未结 9 1006
南旧
南旧 2020-12-13 09:01

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: ca

相关标签:
9条回答
  • 2020-12-13 09:34
    private boolean negate(boolean val) {
        return !val;
    }
    

    I think that is what you are asking for??

    0 讨论(0)
  • 2020-12-13 09:39
    value ^= true;
    

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

    0 讨论(0)
  • 2020-12-13 09:41

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

    booleanVariable = !booleanVariable;
    

    This flips the variable.

    0 讨论(0)
提交回复
热议问题