Why doesn't this method work? Java ternary operator

前端 未结 6 571
情歌与酒
情歌与酒 2020-12-03 03:53

What\'s wrong with this code:

void bark(boolean hamlet) {
    hamlet ? System.out.println(\"To Bark.\") : System.out.println(\"Not to Bark\");
}
6条回答
  •  抹茶落季
    2020-12-03 04:26

    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.

提交回复
热议问题