I'm trying to update softcount for my Blackjack game to account for Aces being played (value 11 or 1). When using the short-form IF statement, why is the first line of code incorrect, but the second line is okay to use? Is this type of if statement limited?
(counter > 1) ? (softcount+=1) : (softcount+=value); // bad
softcount += (counter > 1) ? 1 : value; // good
The ternary has to be seen as a way to evaluate something and not as a way to apply a processing.
So it expects some expressions after ?
but you wrote statements : softcount+=1
and (softcount+=value)
in the first code.
In the second code, it is ok because you specified two expressions : 1
and value
.
Besides do you really find this code a short hand ?
(counter > 1) ? (softcount+=1) : (softcount+=value); // bad
You repeat the increment part.
What you want in your case is just :
if (counter > 1) { softcount+=1;} else {softcount+=value;)
It is simply how the language is defined.
Only certain expressions - statement expressions - can be made into a statement by adding ;
. (Statement expression + ;
is an expression statement ).
From JLS Sec 14.8 :
ExpressionStatement:
StatementExpression ;
StatementExpression:
Assignment
PreIncrementExpression
PreDecrementExpression
PostIncrementExpression
PostDecrementExpression
MethodInvocation
ClassInstanceCreationExpression
Conditional expressions are not statement expressions.
It is called ternary operator, it is used when you simply want to return a value based on condition. It's main purpose is to avoid if else for simple avaluations. In your case you should use if else.
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.