Reputation: 47
An equivalent if statement works (commented out) , but the ternary operator does not.Why is that ?
class Solution {
public String defangIPaddr(String address) {
StringBuilder sb = new StringBuilder();
for (char letter : address.toCharArray()) {
(letter == '.') ? sb.append("[.]") : sb.append(letter);
// if (letter == '.')
// sb.append("[.]");
// else
// sb.append(letter);
}
return sb.toString();
}
}
Upvotes: 1
Views: 89
Reputation: 778
The equivalent for above code is :
sb.append(letter == '.' ? "[.]" : letter);
The conditional operator returns a value instead of executing a statement. That is why you got the syntactical error 'Not a statement' there. You should not use '?' as a replacement for 'if' statement if your plan is to execute a statement instead of returning a value.
Upvotes: 3