문제

In Java (or, to be honest, any computer language), to increment an int, you do as so:

// Option 1 - efficient
int x = 0;
x++;
// x = 1

// Option 2 - works, but is ugly
int y = 0;
y = y + 1;
// y = 1;

How would you do this to a boolean?

// Standard way to
// oppose a boolean
boolean isTrue = false;
if(isTrue){
    isTrue = false;
} else if(!isTrue){
    isTrue = true;
}

Is there not a shortcut to change a boolean? For example, if the boolean was true, is there a way to change it with just a small shortcut like x++;?

도움이 되었습니까?

해결책

You can use ! to flip its value.

isTrue = !isTrue;

! inverts the value of a boolean.

다른 팁

No, there is no such shortcut in Java.

What you can do is use the logical complement operator to reverse the value

!isTrue

but you will have to reassign the result.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top