C Programs Tutorials | IT Developer
IT Developer

Java Programs - Advanced



Share with a Friend

Palindrome Words Program - Java Program

A palindrome is a word that may be read the same way in either direction.

Accept a sentence in uppercase which is terminated by either “.”, “?” or “!”. Each word of the sentence is separated by a single blank space.

Perform the following tasks:
(a) Display the count of palindromic words in the sentence.
(b) Display the palindromic words in the sentence.

Example of palindromic words:
MADAM, ARORA, NOON

Test your program with the sample data and some random data:

Example 1:
INPUT: MOM AND DAD ARE COMING AT NOON.
OUTPUT: MOM DAD NOON
NUMBER OF PALINDROMIC WORDS: 3

Example 2:
INPUT: NITIN ARORA USES LIRIL SOAP.
OUTPUT: NITIN ARORA LIRIL
NUMBER OF PALINDROMIC WORDS: 3

Example 3:
INPUT: HOW ARE YOU?
OUTPUT: NO PALINDROMIC WORDS

import java.io.*; import java.util.StringTokenizer; class Palindrome{ public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Sentence: "); String s = br.readLine(); int count = 0; s = s.trim(); s = s.toUpperCase(); int len = s.length(); char last = s.charAt(len - 1); if(last != \'.\' && last != \'?\' && last != \'!\'){ System.out.println("Invalid sentence."); return; } StringTokenizer st = new StringTokenizer(s, " .?!"); int c = st.countTokens(); for(int i = 1; i <= c; i++){ String word = st.nextToken(); if(isPalindrome(word)){ System.out.print(word + " "); count++; } } if(count > 0) System.out.println("\nNUMBER OF PALINDROMIC WORDS: " + count); else System.out.println("NO PALINDROMIC WORDS"); } public static boolean isPalindrome(String w){ String r = new String(); for(int i = w.length() - 1; i >= 0; i--) r += w.charAt(i); return w.equalsIgnoreCase(r); } }

Output

 
OUTPUT 1:

Sentence: MOM AND DAD ARE COMING AT NOON.
MOM DAD NOON 
NUMBER OF PALINDROMIC WORDS: 3

OUTPUT 2:
Sentence: NITIN ARORA USES LIRIL SOAP.
NITIN ARORA LIRIL 
NUMBER OF PALINDROMIC WORDS: 3

OUTPUT 3:
Sentence: HOW ARE YOU?
NO PALINDROMIC WORDS