What's wrong with this code:
void bark(boolean hamlet) {
hamlet ? System.out.println("To Bark.") : System.out.println("Not to Bark");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With