Question
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
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
import java.util.StringTokenizer;
public class PalindromeSentence
{
public static boolean isPalindrome(String w)
{
int i=0;
String r = "";
for(i = w.length() - 1; i >= 0; i--)
{
r += w.charAt(i);
}
return (w.equalsIgnoreCase(r));
}
public static String generate(String w)
{
int i=0;
String r ="";
for(i = w.length() - 2; i >= 0; i--)
{
r += w.charAt(i);
}
w = w.substring(0, w.length());
return w + r;
}
public static void main(String args[])
{
int i=0,count=0;
char ch=' ';
Scanner sc=new Scanner(System.in);
System.out.print("Sentence: ");
String sen = sc.nextLine().toUpperCase();
ch = sen.charAt(sen.length() - 1);
if(ch != '.' && ch != '?' && ch != '!')
{
System.out.println("INVALID INPUT");
return;
}
StringTokenizer st = new StringTokenizer(sen, " ?.!,");
count = st.countTokens();
String newSen ="";
for(i = 1; i <= count; i++)
{
String word = st.nextToken();
if(isPalindrome(word))
{
newSen += word + " ";
}
else
{
newSen += generate(word) + " ";
}
}
System.out.println(sen);
System.out.println(newSen);
}
}
Coding Store
Sale

ISC QUESTION PAPERS WITH SOLUTION(PROGRAMMING ONLY)
Sale

ICSE QUESTION PAPER WITH SOLUTION(PROGRAMMING ONLY)
Sale

ISC QUESTION PAPERS WITH SOLUTION(PROGRAMMING ONLY)
Sale

ICSE QUESTION PAPER WITH SOLUTION(PROGRAMMING ONLY)
Sale

ISC QUESTION PAPERS WITH SOLUTION(PROGRAMMING ONLY)
Sale
