简体   繁体   English

三元运算符中的多个语句

[英]Multiple Statements in the Ternary Operator

What is the right syntax to have multiple statements in my ternary operator statement? 在三元运算符中包含多个语句的正确语法是什么?

str.length() == 1 ? (str = str.replace(0, str.length(), "00")  && flag = false) : str = str.deleteCharAt(str.length() - 1);

I need to execute a couple of statements when the length of my StringBuilder str is 1 当我的StringBuilder str的长度为1时,我需要执行一些语句

  1. Replace the str with "00" 将str替换为“ 00”
  2. Unset flag 未设置标志

Any help would be greatly appreciated. 任何帮助将不胜感激。

AFAIK it is not possible. AFAIK这是不可能的。 In other languages you can achieve that using the coma operator, but it is not allowed in java. 在其他语言中,您可以使用coma运算符来实现,但是在Java中是不允许的。

That being said, doing more than one action in a ternary operation is usually a very bad practice: Yes you gonna save about 4 or 5 lines of code, but it will be way harder to read, edit, and therefore, to debug. 话虽这么说,在三元操作中执行多个动作通常是一个非常糟糕的做法:是的,您将节省大约4或5行代码,但是这将更难以阅读,编辑和调试。

If you absolutely must do it with one ternary operator that's how it can be done : 如果您绝对必须使用一个三元运算符来做到这一点,那么可以这样做:

flag = str.length() == 1 ?
    str.replace(0, str.length(), "00") == null :
    str.deleteCharAt(str.length() - 1) != null && flag;

Good luck getting it through a code review. 祝您好运,通过代码审查获得它。 As others have suggested, an if statement makes sense here : 正如其他人所建议的,if语句在这里很有意义:

if (str.length() == 1) {
     flag = false;
     str.replace(0, str.length(), "00");
} else {
     str.deleteCharAt(str.length() - 1);
}

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

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