Reputation: 1242
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
Any help would be greatly appreciated.
Upvotes: 7
Views: 24109
Reputation: 22224
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);
}
Upvotes: 3
Reputation: 7660
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.
Upvotes: 5