简体   繁体   English

如何在Java中使用三元运算符编写嵌套条件?

[英]how to write nested condition using ternary operator in java?

Can we write like this using ternary operator? 我们可以使用三元运算符这样写吗? When I wrote like this I am getting error,Please help me.How can I write correct syntax? 当我这样写时,我遇到错误,请帮助我。如何编写正确的语法?

(str.charAt(j)==c.charAt(k++)) ? break: k<len1 ? continue:break L1;

Ternary operator is a part of expression and its components must be expressions as well, not the statements . 三元运算符是表达式的一部分,其组成部分也必须是表达式 ,而不是语句 In this case you can easily use if stamement: 在这种情况下, if出现问题,您可以轻松使用:

if (str.charAt(j)==c.charAt(k++)) 
    break;
else if (k<len1)
    continue;
else 
    break L1;

Or even simpler: 甚至更简单:

if (str.charAt(j)==c.charAt(k++)) 
    break;
if (k<len1)
    continue;
break L1;

break & continue are always used within a loop; 中断和继续总是在循环内使用; You you might want to recheck your logic. 您可能需要重新检查逻辑。

If you want to write a nested ternary operator the general syntax would be 如果要编写嵌套三元运算符,则一般语法为

boolean x=("a".equals("b"))? false: (("b".equals("c"))?true:false);
System.out.println(x);

Output 输出量

false

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

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