where all variables are int or int array.
How does the ternary operator work in java with +=? This is my understanding:
so it is score += round[i] == i+start or == 0.
Is this a correct understanding?
Kind regards, James
As with any combination of operators, it's a question of operator precedence and (where the operators have the same precedence) associativity. In Java, the simple assignment and all the operator/assignment operators share the lowest precedence tier. The ternary operator is the sole occupant of the next higher precedence tier. Therefore, your expression is equivalent to
score += ((rounds[i]) ? (i + START) : 0)
That is, the ternary expression is evaluiated, and its result is the right-hand operand of the +=
.
As others have observed, that's not valid in Java if the type of rounds[i]
is int
, though that would be ok in C. But the expression could be sensible in Java if rounds[i]
were an array of boolean
, or it could be rewritten like this...
score += ((rounds[i] != 0) ? (i + START) : 0)
... on the assumption that a C-style boolean interpretation of integer rounds[i]
is what is wanted.
score += (some condition which is true or false) ? value to add if true : value to add if false;
We can try it.
int START = 3;
int score = 0;
boolean[] rounds = { true, false };
for (int i = 0; i < rounds.length; i++) {
score += (rounds[i]) ? i + START : 0;
System.out.format("i is %d, score is %d%n", i, score);
}
Output:
i is 0, score is 3 i is 1, score is 3
So the first time through the loop i
is 0 and rounds[i]
is true
. In this case Java adds i
and START
to get 3 and adds this to score
. Second time i
is 1
and rounds[i]
is false
, so instead just 0 is added.
The statement you ask about adds a value to score
. The value added is i + START
if rounds[i]
can be evaluated to true and 0 if it's false
. If i
and START
are both numeric, a number will be added. If score
is numeric, adding 0 usually makes no difference, so you may think of the statement as adding a value only if rounds[i]
is true.
so it is score += round[i] == i+start or == 0.
No, there is no implicit ==
comparison in the statement (as others have said, it requires that rounds[i]
is a Boolean value, true or false).
The ternary operator ?:
is used as follows:
int start = 5;
// In this case, start was added to itself to obtain 10.
start += true ? start : 0;
System.out.println(start); // prints 10
// with out the compound assignment operator (+=) the
// expression should be enclosed in ()
start = start + (true ? start : 0);
System.out.println(start); // prints 20
In the above cases, if the boolean was false, the start
always have the value 5
since 0
would be added each time.
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.