java三元表达式必须返回_java – 三元运算符的右手表达式必须兼容...

您的方法声明返回类型是String.任何return语句都必须生成一个与声明的返回类型兼容的表达式.

但是,在这种情况下,返回类型可以是int,这解释了编译器拒绝它的原因.

这不是特定于三元运算符的,它也可以使用等效的if / else块进行复制:

if(distance < 1000)

return "train"; //This part is valid

else

return 10; //This line will be rejected by the compiler

出于同样的原因,最后一行将无法编译.这只是因为基本的类型检查.

System.out.println(distance < 1000 ? “train” : 10); compiles and runs without a problem.

这是因为编译器检测到String和int的公共类型,即Object,并解析为选择此签名:

java.io.PrintStream#println(Object x) // available in the target class

但是,这不适用于方法返回类型.

如果将返回类型更改为Object,则代码也会编译.但那当然不是你想要做的.

Ternary operations require both right-hand expressions to be of compatible data types

– &GT;这部分实际上是有效的.这是解释它的方法:两个表达式中的每一个必须是单独兼容的:

String value = distance > 1000 ?

"train" //this must be compatible with String

:

10 //this too must be compatible with String (it isn't)

相反:

Object value = distance > 1000 ?

"train" //this must be compatible with Object (it is)

:

10 //this too must be compatible with Object (it is)

换句话说,对System.out.println的调用(距离< 1000?“train”:10)类似于上面的最后一个例子,其中期望的类型与两个表达式兼容.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值