Java program that reads each word from the file and outputs the number of palindromes in the file
Create a file WordBuff.txt that contains the following list of words: MADAM,
DAD, RISK, JAVA, MALAYALAM, RACECAR, RADAR, ROTOR, REFER,
SEDES, SOLOS, COURSE, STATS, TOROT, TENET, MACHINE, VIRTUAL,
STUDENT, PULLUP, PROGRAMME, and CORE. Write a java program that reads
each word from the file and outputs the number of palindromes in the file.
Answer:
import java.io.FileInputStream;
import java.util.Scanner;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Question8
{
public static void main(String[] args)
{
String word;
Scanner inputStream;
char lastChar;
int maxConsecutive = 0;
String maxWord = "";
try
{
inputStream = new Scanner(new FileInputStream("words.txt"));
while (inputStream.hasNextLine())
{
word = inputStream.nextLine();
int numConsecutive = 0;
lastChar = word.charAt(0);
int i = 1;
while (i < word.length() -1) { if (word.charAt(i)==lastChar) { numConsecutive++; // check if at end of string; if so, no more pairs if (i >= word.length() -2)
break;
// Move forward 2 chars looking for next pair
lastChar = word.charAt(i+1);
i+=2;
}
else
{
lastChar = word.charAt(i);
i++;
}
}
if (numConsecutive > 0)
{
if (numConsecutive > maxConsecutive)
{
maxWord = word;
maxConsecutive = numConsecutive;
}
}
}
inputStream.close();
System.out.println(maxWord +
" is the word with the most consecutive letters at " +
maxConsecutive);
}
catch (IOException e)
{
System.out.println("Error reading files.");
}
}
}
Leave a reply