Search code examples
javastringfor-looppalindromecharat

Trying to create a palindrome...how can I compare the "output.charAt(k)" to original "output" String?


public static void main(String[] args) {
    String input = new String(JOptionPane.showInputDialog("Enter a string."));
    String inputLow = input.toLowerCase();

    String output = "";     //Blank string
    for(int i = 0; i < inputLow.length(); i++)  //For loop to continue through the entered string
    {
        if(inputLow.charAt(i) >= 'a' && inputLow.charAt(i) <= 'z')  //If statement to check for appropriate characters only
        {
            output += inputLow.charAt(i);   //Add only the appropriate characters to String output ('a' - 'z')
        }
    }
    System.out.println(output);

    //GETTING REVERSE STRING
    int n = output.length() - 1;
    String last = "";
    for(int k = n; k >= 0; k--)
    {
        System.out.print(output.charAt(k));
        //last = String.valueOf(output.charAt(k));
    }
    //System.out.println("");
//System.out.println(last);
}

So I was trying to print the String last but when I un-comment that code it outputs with this:

heyman
namyeh
h

But I want it to print "heyman" on the third line. (I am only doing the print statements to test if it is doing it correctly, and my goal is to compare String last to String output and if they are the same then it is a Palindrome, otherwise it's not.)

How can I do this with specifically this method (or something almost like it)?


Solution

  • You're setting the value of last to one character at a time. You're basically resetting it every time, which is why it ends on the last character of the reversed string (which is the first character).

    Change it to last = String.valueOf(output.charAt(k)) + last;