Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’ or ‘!’ only. The words are to be separated by a single blank space and are in uppercase.
Perform the following tasks:
(a) Check for the validity of the accepted sentence.
(b) Convert the non-palindrome words of the sentence into palindrome words by concatenating the word by its reverse (excluding the last character).
Example: The reverse of the word HELP would be LEH (omitting the last alphabet) and by concatenating both, the new palindrome word is HELPLEH. Thus, the word HELP becomes HELPLEH.
Note: The words which end with repeated alphabets, for example ABB would become ABBA and not ABBBA and XAZZZ becomes XAZZZAX.
Palindrome word: Spells same from either side. Example: DAD, MADAM, etc.
(c) Display the original sentence along with the converted sentence.
Test your program for the following data and some random data:
Example 1
INPUT:
THE BIRD IS FLYING.
OUTPUT:
THE BIRD IS FLYING.
THEHT BIRDRIB ISI FLYINGNIYLF
Example 2
INPUT:
IS THE WATER LEVEL RISING?
OUTPUT:
IS THE WATER LEVEL RISING?
ISI THEHT WATERETAW LEVEL RISINGNISIR
Example 3
INPUT:
THIS MOBILE APP LOOKS FINE.
OUTPUT:
THIS MOBILE APP LOOKS FINE.
THISIHT MOBILELIBOM APPA LOOKSKOOL FINENIF
Example 4
INPUT:
YOU MUST BE CRAZY#
OUTPUT:
INVALID INPUT
import java.util.Scanner;
class Convert{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("ENTER THE SENTENCE: ");
String s = in.nextLine().toUpperCase();
if(!valid(s)){
System.out.println("INVALID INPUT");
return;
}
String p = "";
String w = "";
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(Character.isLetterOrDigit(ch))
w += ch;
else{
p += toPalindrome(w) + " ";
w = "";
}
}
System.out.println(s);
System.out.println(p);
}
public static boolean valid(String s){
char last = s.charAt(s.length() - 1);
if(".?!".indexOf(last) == -1)
return false;
if(s.indexOf(" ") >= 0)
return false;
return true;
}
public static String toPalindrome(String w){
int i = 0;
int j = w.length() - 1;
while(i < j){
if(w.charAt(i) == w.charAt(j)){
i++;
j--;
}
else
break;
}
if(i >= j)
return w;
String p = new String(w);
int index = w.length() - 2;
while(index - 1 >= 0 && w.charAt(index) == w.charAt(index + 1))
index--;
for(i = index; i >= 0; i--)
p += w.charAt(i);
return p;
}
}