Write a program to read several lines from a file called H.in. For each line, ch
ID: 3805057 • Letter: W
Question
Write a program to read several lines from a file called H.in. For each line, check whether it is a palindrome. For each line read from the file, print only the lines that are palindromes. Recall that a palindrome is a string that is the same backwards and forwards, ignoring spaces and punctuation. Some example palindromes are “radar” and “I, Madam, I made radio. So I dared! Am I mad? Am I??” You may use theremoveWS method from Lab. Your palindrome checking method must be recursive. In JAVA:
removeWS :
public static String removeWS(String a)
{
if (a.length() == 0)
return a;
String b = Character.isLetterOrDigit(a.substring(0, 1).charAt(0)) ? a.substring(0, 1) : "";
return b + removeWS(a.substring(1));
}
}
H.in:
You must be the change you want to see in the world
Sore was I, ere I saw Eros.
A man, a plan, a canal -- Panama
Never a foot too far, even.
BORROW - OR ROB?
Euston SaW I was not Sue.
THIS IS JUST A TEST.
"Stop!" nine myriad murmur. "Put up rum, rum, dairymen, in pots."
Live on evasions?! No, I save no evil.
Red Roses run no risk, sir, on nurses order.
The best way out is always through........
Explanation / Answer
import java.io.*;
import java.lang.*;
public class palindrome {
public static String removeWS(String a)
{
if (a.length() == 0)
return a;
String b = Character.isLetterOrDigit(a.substring(0, 1).charAt(0)) ? a.substring(0, 1) : "";
return b + removeWS(a.substring(1));
}
public static boolean isPalindrome(String s)
{
int l = s.length();
for(int i=0,j=l-1;i<j;i++,j--)
{
if(Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j)))
{
return false;
}
}
return true;
}
public static void main(String[] args)
{
String fName = "/Users/Rajeev/chegg/H.in";
String line,nline;
try {
FileReader fReader = new FileReader(fName);
BufferedReader bReader = new BufferedReader(fReader);
while((line = bReader.readLine()) != null) {
nline = removeWS(line);
if(isPalindrome(nline))
{
System.out.println(line);
}
}
bReader.close();
}
catch(Exception ex) {
System.out.println("Error occured");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.