Is it possible to convert the below java code using ternary operator:
if (x > 0) {
a = 100;
b = 100;
} else {
a = 1;
b = 1;
}
You can write:
a = b = x > 0 ? 100 : 1;
but only because you assign the same value to a
and b
.
In the general case, you'd need a separate ternary conditional operator for each variable you wish to assign to:
a = x > 0 ? 100 : 1;
b = x > 0 ? 100 : 1;
You can handle this with one ternary expression:
a = x > 0 ? 100 : 1;
b = a;
This works because the assignment logic for both a
and b
happens to be the same. If that were not the case, we would need two separate ternary expressions:
a = x > 0 ? 100 : 1;
b = x > 0 ? 100 : 1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.