Why doesn't this method work? Java ternary operator

你说的曾经没有我的故事 提交于 2019-12-17 10:54:34

问题


What's wrong with this code:

void bark(boolean hamlet) {
    hamlet ? System.out.println("To Bark.") : System.out.println("Not to Bark");
}

回答1:


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" );
}



回答2:


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.




回答3:


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.




回答4:


I should imagine its because the ternary operator is expecting to assign a value. Try this:

void bark(boolean hamlet) {
    String result = hamlet ? "To Bark!" : "Not to Bark";
    System.out.println(result)
}



回答5:


A ternary statement has to return something, you could use an if here:

void bark(boolean hamlet)
{
  if (hamlet)
  {
    System.out.println("To Bark.")
  }
  else
  {
     System.out.println("Not to Bark");
  }
}



回答6:


Ternary operators must return something. So you can put it inside the print statement like such:

void bark(boolean hamlet) 
{
    System.out.printf("%s\n", hamlet ? "To Bark." : "Not to Bark");
}

Or:

void bark(boolean hamlet) 
{
    System.out.println(hamlet ? "To Bark." : "Not to Bark");
}


来源:https://stackoverflow.com/questions/16876698/why-doesnt-this-method-work-java-ternary-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!