// This program finds all palindromes in a dictionary file
//  -- M. Branicky, 10/26/06, 10/24/07

import java.util.Scanner; // needed for input processing using Scanner
import java.io.File;      // needed for File class

public class Palindromes {
  // Returns true if String s is a palindrome,
  // i.e., reads the same forward as backward
  // E.g., "kayak", "noon", "pop", "a", "", ...
  //
  // Reference: Y.D. Liang, Intro. to Java Programming, 6/e, p. 270
  //
  public static boolean isPalindrome (String s) {
    int low, high;
    // start with the first and last letters
    low = 0;  
    high = s.length()-1;
    while (low<high) {
      // check the current pair
      if (s.charAt(low) != s.charAt(high)) {
        return false;
      } 
      // move each in from the ends
      low++;
      high--;
    }
    // all pairs have matched (or string has length <= 1)
    return true;  // it is a palindrome
  }

  //            for file-error handling: vvvvvvvvvvvvvvvv
  public static void main(String args[]) throws Exception {
    // Open the file
    // File available for download in the ENGR 131 Code Repository
    // http://dora.case.edu/msb/131/code/words.txt (414KB)
    File infile = new File("words.txt");
    Scanner input = new Scanner( infile );

    // Read each word (one word per line) from the input file
    while (input.hasNext()) {
      String word = input.nextLine();

      // Display palindromes
      if (isPalindrome(word)) {
        System.out.printf("Found a palindrome: %s\n", word);
      }
    }

    // Close the file
    input.close();
  }
}
