简体   繁体   中英

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

  1. Replace the str with "00"
  2. Unset flag

Any help would be greatly appreciated.

AFAIK it is not possible. In other languages you can achieve that using the coma operator, but it is not allowed in 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.

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 (str.length() == 1) {
     flag = false;
     str.replace(0, str.length(), "00");
} else {
     str.deleteCharAt(str.length() - 1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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