Search code examples
javastringpalindrome

How to print word backwards


So I am checking a word input to see if it is a palindrome. The error in my code seems to be with the comparing of the two strings. I used the .equals() to test values for equality but it doesn't work. Any ideas?

Here is my code:

public class PalindromeTask08 
{

public static void main(String[] args) 
{
    Scanner in = new Scanner (System.in);
    int count = 5;
    int x =0;

    //loops to input a word 
    do{
        System.out.println("input a word");
        String answer = in.next();
        char[] wordBackwards=new char[answer.length()];


        System.out.printf("The lenght of the word inputted is: %s%n", answer.length());

        for(int i= answer.length() ; i>0 ; --i)
        {

            wordBackwards[x] = answer.charAt(i-1);
            x++;
        }

        x=0;

        wordBackwards.toString();
        System.out.println(wordBackwards);

        if (answer.equals(wordBackwards))
        {
            System.out.printf("%s is a palindrome", answer);
            --count;
            System.out.printf("you have %d more attempts", count);
        }
        else
        {
            System.out.printf("%s is NOT a palindrome", answer);
            --count;
            System.out.printf("you have %d more attempts", count);

        }

    }while(count!=0);
    in.close();



    }

}

Solution

  • Your problem is

    wordBackwards.toString();
    

    It doesn't do any thing other that returning you the array address.
    You need to replace it like this to make it work:

    ...
    x=0;
    String backWordsString = new String(wordBackwards);
    System.out.println(backWordsString);
    if (answer.equals(backWordsString)) {
    ...
    

    An easier way to do it would be

    public class PalindromeTask08 {
        public static void main(String[] args) {
            Scanner in = new Scanner (System.in);
            int count = 5;
            int x =0;
    
            //loops to input a word 
            do {
                System.out.println("input a word");
                String answer = in.next();
                if (answer.equals(new StringBuilder(answer).reverse().toString())) {
                    System.out.printf("%s is a palindrome", answer);
                } else {
                    System.out.printf("%s is NOT a palindrome", answer);
                }
                --count;
                System.out.println("\n you have %d more attempts "+ count);
            } while(count!=0);
            in.close();
        }
    }
    

    To read more about the StringBuilder.