javafor-loopappendstringbuildercharat

Why am I getting the original word plus the reverse word?


My return for the input "no" is showing up as "noon" I'm seeing where it is adding the original word to the StringBuilder. How do I get it to not do that, and only add the characters to an empty StringBuilder, in reverse?

public class Palindrome
{
    public static String reversed(String originalWord)
    {
        int lengthOfWord = originalWord.length();
        StringBuilder reversedWordBuilder = new StringBuilder(originalWord);

        for (int currentChar = lengthOfWord-1; currentChar >= 0; currentChar--)
        {
            reversedWordBuilder.append(Character.toString(originalWord.charAt(currentChar)));
        }
        
        return reversedWordBuilder.toString();
    }
}

Solution

  • You are initializing the StringBuilder with the originalWord itself:

    StringBuilder reversedWordBuilder = new StringBuilder(originalWord);
    

    so it already have initial a value of "no", then you append the reversed one to it. You should initialize it with empty constructor like:

    StringBuilder reversedWordBuilder = new StringBuilder();
    

    and then to do your logic in the loop.

    Since you already use StringBuilder you can do in one liner as it follows:

    public static String reversed(String originalWord) {
    
        return new StringBuilder(originalWord).reverse().toString();
    }