Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
value ^= true;

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...