Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’ or ‘!’ only. The words may be separated by a single blank space and should be case-insensitive.
Perform the following tasks:
(a) Check if the sentence is a Palindrome Sentence. A sentence is a Palindrome Sentence if, after removing the spaces and punctuation, the letters read the same forward and backward. Example: “Never odd or even.”
(b) Display the first-occurring most frequent word in the sentence (in lowercase). If there is a tie, choose the word that appears first in the sentence and if no words are repeated then print NONE.
Test your program for the following data and some random data:
Example 1
INPUT: No lemon no melon.
OUTPUT:
IT IS A PALINDROME SENTENCE.
MOST FREQUENT WORD: no
Example 2
INPUT: Was it a car or a cat I saw?
OUTPUT:
IT IS A PALINDROME SENTENCE.
MOST FREQUENT WORD: a
Example 3
INPUT: It is a rainy day!
OUTPUT:
IT IS NOT A PALINDROME SENTENCE.
MOST FREQUENT WORD: NONE
Example 4
INPUT: Always be careful#
OUTPUT:
INVALID INPUT
import java.util.Scanner;
class Palindrome{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Sentence: ");
String s = in.nextLine();
char last = s.charAt(s.length() - 1);
if(".?!".indexOf(last) == -1){
System.out.println("INVALID INPUT");
return;
}
String str = "";
int count = 0;
if(s.length() > 0)
count = 1;
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(ch == ' ')
count++;
}
String a[] = new String[count];
int f[] = new int[count];
String word = "";
int index = 0;
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(Character.isLetterOrDigit(ch)){
str += ch;
word += ch;
}
else{
a[index++] = word;
word = "";
}
}
boolean isPalindrome = true;
for(int i = 0, j = str.length() - 1; i <= j; i++, j--){
char ch1 = Character.toLowerCase(str.charAt(i));
char ch2 = Character.toLowerCase(str.charAt(j));
if(ch1 != ch2){
isPalindrome = false;
break;
}
}
if(isPalindrome)
System.out.println("IT IS A PALINDROME SENTENCE");
else
System.out.println("IT IS NOT A PALINDROME SENTENCE");
int highest = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a.length; j++){
if(a[i].equalsIgnoreCase(a[j]))
f[i]++;
}
if(f[i] > highest)
highest = f[i];
}
String most = "";
for(int i = 0; i < f.length; i++){
if(f[i] == highest && f[i] > 1){
most = a[i];
break;
}
}
if(most.length() > 0)
System.out.println("MOST FREQUENT WORD: " + most.toLowerCase());
else
System.out.println("MOST FREQUENT WORD: NONE");
}
}