zulu-700
zulu-700

Reputation: 47

Why is this ternary statement giving me a syntax error?

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

Answers (1)

Jerin D Joy
Jerin D Joy

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

Related Questions