Pretty much what the title says, I have a hard time comprehending this expression, would be grateful if anyone explained the idea behind this expression.
Asked
Active
Viewed 90 times
-1
-
Try grouping the terms in parentheses and see if that makes it clearer. – chrylis -cautiouslyoptimistic- Jul 19 '18 at 18:03
-
4Which part of the expression confuses you? Would parenthesis help? `sum += (digit > 9 ? digit - 9 : digit);`. Expression uses `>` comparison operator, `-` subtraction operator, `? :` ternary conditional operator, and `+=` additive-assignment operator. Which of these don't you know? – Andreas Jul 19 '18 at 18:03
-
In short, it is a way of writing if-statement, just like how you write if-statement in MS Excel. – user3437460 Jul 19 '18 at 18:06
-
Read about Java Ternary Operators https://alvinalexander.com/java/edu/pj/pj010018 – Benjamin RD Jul 19 '18 at 18:09
2 Answers
6
This is ternary operation it is the same as a if else in one expression;
The statement: sum += digit > 9 ? digit - 9 : digit;
Is the same as:
if (digit > 9)
sum += digit - 9;
else
sum += digit;

Marcos Vasconcelos
- 18,136
- 30
- 106
- 167
0
It is a Java Ternary Operator
Basically if the Sum + digit
is greater than 9 than sum will equal digit-9
OR if not it will just equal digit
So this is same as
if (digit > 9)
sum += digit - 9;
else
sum += digi

Kartik Shandilya
- 3,796
- 5
- 24
- 42

marshall legend
- 474
- 1
- 6
- 13
-
Not quite. If digit > then `sum = sum + digit -9` else `sum = sum + digit` – scrappedcola Jul 19 '18 at 18:07
-
Oh yes, you're correct. I forgot to account for the `+=` operation. Thank you @scrappedcola for catching my mistake and correcting it. – marshall legend Jul 19 '18 at 18:09