Why doesn't this method work? Java ternary operator
Ternary operators can't have statements that don't return values, void
methods. You need statements that have return values.
You need to rewrite it.
void bark(boolean hamlet) {
System.out.println( hamlet ? "To Bark." : "Not to Bark" );
}
You can read why in the Java Language Specification, 15.25. Conditional Operator ? :
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
You need to do as several of the other answers suggest, and apply the conditional operator to just the argument.
According to §JLS.15.25:
ConditionalExpression: ConditionalOrExpression ConditionalOrExpression ? Expression : ConditionalExpression
The conditional operator is syntactically right-associative (it groups right-to-left). Thus, a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).
The conditional operator has three operand expressions. ? appears between the first and second expressions, and : appears between the second and third expressions.
The first expression must be of type boolean or Boolean, or a compile-time error occurs.
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.