In java, can we use both else and else if in ternary operator and construct 3 conditions in the same statement?

huangapple go评论69阅读模式
英文:

In java, can we use both else and else if in ternary operator and construct 3 conditions in the same statement?

问题

例如,

int number = 10;

number > 9 && number < 100 ? "two digit number" : "not a two digit number";

结果为:two digit number。

但如果数字大于9且小于100,我想要打印出语句:"two digit number",并且在同一语句中,不需要额外的条件代码。

我们可以使用if和elseif语句来实现这一点。但在Java中是否有使用三元运算符的方法来做到这一点呢?

英文:

for example,

int number = 10;

number &gt; 99 &amp;&amp; &lt; 1000 ? &quot;three digit number&quot; : &quot;not a three digit number&quot;;

result is : not a three digit number.

but i want to print a statement "two digit number" if the number is > 9 and less than 100,
in the same statement without requiring a seperate condition to code.

we can do this with if and elseif statements.
but is there a way to do this with ternary operator in java?

答案1

得分: 0

我认为第二个三元表达式作为“else”条件可以实现你寻找的结果:

int number = 10;
String result = number > 99 && number < 1000 ? "三位数" :
        (number > 9 && number < 100 ? "两位数" : "不是两位或三位数");

请注意,与等效的if/else if代码块相比,这可能被认为不太易读,因此这是一种需要谨慎使用的技术。

英文:

I believe a second ternary expression as the "else" condition achieves the result you're looking for:

int number = 10;
String result = number &gt; 99 &amp;&amp; number &lt; 1000 ? &quot;three digit number&quot; :
        (number &gt; 9 &amp;&amp; number &lt; 100 ? &quot;two digit number&quot; : &quot;not a two or three digit number&quot;);

Note that this may be considered less readable than the equivalent if/else if block, so this is a technique to use sparingly.

答案2

得分: 0

你可以在三元操作符中使用嵌套的三元操作,如果想要在三元运算符中使用 else-if,但请注意这会降低可读性。

int num = 5;
String result = (num > 9) ? ((num > 99 && num < 1000) ? "三位数" : "两位数") : "个位数";
System.out.println("结果 = " + result);
英文:

You can use Nested Ternary operation if you want to use else-if in ternary operator, but note this is less readable.

int num = 5;
String result = (num &gt; 9)?((num&gt;99 &amp;&amp; num&lt;1000)?&quot;Three digit number&quot;:&quot;Two digit number&quot;):&quot;Single digit number&quot;;
System.out.println(&quot;Result = &quot;+result);

huangapple
  • 本文由 发表于 2020年10月20日 13:42:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64439118.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定