Palindrome Words ISC Computer Science 2013 Practical

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.util.Scanner;
class Palindrome{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("Enter the sentence: ");
        String s = in.nextLine().toUpperCase();
        char last = s.charAt(s.length() - 1);
        if(".?!".indexOf(last) == -1){
            System.out.println("INVALID INPUT");
            return;
        }
        int count = 0;
        String word = new String();
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(Character.isLetterOrDigit(ch))
                word += ch;
            else{
                String rev = reverse(word);
                if(word.equals(rev)){
                    System.out.print(word + " ");
                    count++;
                }
                word = new String();
            }
        }
        if(count == 0)
            System.out.println("NO PALINDROMIC WORDS");
        else
            System.out.println("\nNUMBER OF PALINDROMIC WORDS: " + count);
    }
    public static String reverse(String w){
        String r = "";
        for(int i = w.length() - 1; i >= 0; i--)
            r += w.charAt(i);
        return r;
    }
}

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory