PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] Why am I getting the original word plus the reverse word?

 May 13, 2022     append, charat, for-loop, java, stringbuilder     No comments   

Issue

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();
}


Answered By - Deyvid Dimitrov
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing