简体   繁体   English

在Java中将if / else-if / else转换为三元运算符

[英]Converting if/else-if/else to ternary operator in Java

I'm trying to convert an if-else statement to an equal statement using the ternary operator ?-: 我正在尝试使用三元运算符将if-else语句转换为相等的语句?-:

My goal is to convert this code: 我的目标是转换此代码:

if (s instanceof Class1) {
    do_something((Class1) s);
} else if (s instanceof Class2) {
    do_something_else((Class2) s);
} else {
    do_that((Class3) s);
}

I worked out something like this: 我做了类似这样的事情:

(s instanceof Class1) ? do_something((Class1) s):
                     ((s instanceof Class2) ? (do_something_else(Class2) s))) :
                     (do_that((Class3) s));

The three methods I call just return void. 我调用的三种方法只返回void。

I get some syntax error when I write it. 我写这个时遇到一些语法错误。 Can someone help or explain what am I missing? 有人可以帮助或解释我错过了什么吗? Thanks in advance 提前致谢

There are two reasons you can't do that: 有两个原因你不能这样做:

  1. You can't use just any freestanding expression as a statement. 您不能仅使用任何独立表达作为声明。 Unlike some languages (JavaScript, for instance), Java doesn't have the general concept of an "expression statement," there are only some expressions that are also allowed as statements (like method calls). 与某些语言(例如JavaScript)不同,Java没有“表达式语句”的一般概念,只有一些表达式也允许作为语句(如方法调用)。

  2. The conditional operator must have a result, but if your methods are void , they don't produce one. 条件运算符必须有结果,但如果您的方法void ,则它们不会产生结果。

Just keep the if / else . 只需保留if / else


Side note: A series of if / else with instanceof tends to suggest a design issue that it may be possible to address in a cleaner way. 旁注:一系列带有instanceofif / else倾向于提出一个设计问题,它可能以更清洁的方式解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM