Display Palindrome Words from a given List of Words

Write a program in Java to keep inputting words from the user as long as the user wants, and finally display all those words that are palindromes.

A palindrome word is a word that remains unchanged even when reversed.

For example, the words like MOM, DAD, etc.

The user must be given a choice (yes or no) so that he/she can continue to enter words as long as it is required.

The result should be displayed only after all the words are entered.

import java.io.*;
class Palindromes{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        char choice = 'y';
        String p = "";
        while(choice == 'y' || choice == 'Y'){
            System.out.print("Enter the word: ");
            String word = br.readLine();
            word = word.trim();
            word = word.toUpperCase();
            if(word.indexOf(' ') > 0)
                word = word.substring(0, word.indexOf(' '));
            if(isPalindrome(word))
                p += word + ", ";
            System.out.print("Continue? Enter y for yes: ");
            choice = br.readLine().charAt(0);
        }
        System.out.println("List of palindrome words:");
        p = p.substring(0, p.lastIndexOf(','));
        System.out.println(p);
    }
    public static boolean isPalindrome(String w){
        String rev = "";
        for(int i = w.length() - 1; i >= 0; i--)
            rev += w.charAt(i);
        return w.equals(rev);
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.