In: Computer Science
Write a Java program that will test lines of text to see if they are palindromes. The program should prompt the user for the name of a file to process, then open and read the file of possible palindromes (one per line of text). The program should then print the total number of lines read, and total number of palindromes.
======
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String args[]) {
try {
BufferedReader brRead = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter file path:");
String filePath = brRead.readLine();
int palCount = 0, lines = 0;
File file = new File(filePath);
FileReader fr = new FileReader(file); // reads the file
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
boolean pal = isPallindrome(line);
if(pal == true)
palCount++;//count pallindorme
lines++;//count number of lines.
}
fr.close();
System.out.println("Number of Pallindromes: " + palCount);
System.out.println("Number of Lines Read: " + lines);
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean isPallindrome(String str) {
StringBuilder sb = new StringBuilder(str);
sb.reverse();
String rev = sb.toString();
if (str.equals(rev)) {
return true;
} else {
return false;
}
}
}
Input
=====
My name is Pill
Tom isi moT
Harry say yas yrraH
Rosie is blue
Output:
======
Enter file path:E://Demo.txt
Number of Pallindromes: 2
Number of Lines Read: 4
Screenshot for reference:
====================