I was wondering if someone could point me in the right direction.
I have an external text file with like over 400,000 words, and the aim is to print out each word that is a palindrome, which I did, but now I am trying to figure out how to collect the 10 longest palindromes out of all the palindromes which are printed to the console, and separate the top 10, by printing them to the console as well.
If someone could get me started, I'm drawing a blank!
Here is the code I have:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
// store external text file into a new File object
File file = new File("dict.txt");
try {
// new Scanner object to read external file
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
// read each word so long as there is a word on subsequent line
String word = sc.nextLine();
// if the word is a palindrome
if (isPalindrome(word)) {
// print out the palindrome word to console
System.out.println(word + " is a palindrome");
}
}
} catch(FileNotFoundException fnfe) {
// if file is not found, print error to console
System.out.println(fnfe.toString());
}
} // end main
public static boolean isPalindrome(String word) {
// if there is no word
if (word == null || word.length() == 0) {
// return false
return false;
}
// StringBuilder to hold a variable of the reverse of each word
String reverse = new StringBuilder(word).reverse().toString();
// if the reversed word equals the original word
if (reverse.equals(word)) {
// it is a palindrome
return true;
}
// return false if no palindrome found
return false;
} // end isPalindrome
} // end class Palindrome
Thanks in advance for any advice!