SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Flow Of Control
Exercise:
Programming Projects
Question:13 | ISBN:9780132830317 | Edition: 5

Question

The file words.txt on the book’s website contains 87,314 words from the English language. Write a program that reads through this file and finds the longest word that is a palindrome.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

// LongestPalindromeWord.java
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class LongestPalindromeWord
{
	public static void main(String[] args)
	{
		Scanner fileIn = null;
		try
		{
			fileIn = new Scanner(new FileInputStream("words.txt"));
		}
		catch (FileNotFoundException e)
		{
			System.out.println("File not found.");
			System.exit(0);
		}
				
		String word;
		boolean palindrome;
		String longestPalindromeWord = "";
				
		while(fileIn.hasNext())
		{
			word = fileIn.next();			
			
			if(word.length() > longestPalindromeWord.length())
			{
				palindrome = true;
				
				for(int i = 0; i < word.length() / 2; i++)
				{
					if(word.charAt(i) != word.charAt(word.length() - 1 - i))
					{
						palindrome = false;
						break;
					}
				}
				
				if(palindrome == true)
				{
					longestPalindromeWord = word;					
				}
			}
		}		
		fileIn.close();
		
		System.out.println("Longest Palindrome Word: " + longestPalindromeWord);
	}
}

Output:

Longest Palindrome Word: malayalam

 

0 0

Discussions

Post the discussion to improve the above solution.