I am trying to write a program that reads a file containing a list of words, and will tell the user if the word is a palindrome or not. Where am I going wrong with this code? The output says they are all palindromes, which they are not.

I have tried changing the loops. I am starting to think it may be the while loop, but I need this to scan the file.

  File file = new File("dictionary.txt");
  Scanner INPUT = new Scanner(file); 

  while (INPUT.hasNextLine()) {      

         String forward = INPUT.nextLine(); String reverseText = forward;

        for(int i = forward.length() - 1; i >= 0; i--)
        reverseText += forward.charAt(i);

    if (reverseText.equals(forward))     
        System.out.println(forward + " is a palindrome");        
    else    
        System.out.println(forward + " is not a palindrome");
    }     

I have watched some youtube videos and read a lot of code snippets. I am new to Java, but it seems the palindrome code is correct. So is it the reading of the file that is the problem?

1 Answers

0
Community On

You need to set the first variable to an empty string then add to it. Also, you will need to make the input string lowercase otherwise the equals comparison will take into account uppercase characters(ie Redder ≠ reddeR). Another thing to consider is removing whitespace(space and tabs at the end of a string) as it will ruin the comparison.

        File file = new File("dictionary.txt");
        Scanner INPUT = new Scanner(file);

        while (INPUT.hasNextLine()) {

            String forward = INPUT.nextLine().toLowerCase().trim();
            String reverseText = "";

            for(int i = forward.length() - 1; i >= 0; i--)
                reverseText += forward.charAt(i);

            if (reverseText.equals(forward))
                System.out.println(forward + " is a palindrome");
            else
                System.out.println(forward + " is not a palindrome");
        }