Palindromes are words spelled the same way backwards as they are forwards such as dad or mom

Palindromes are words spelled the same way backwards as they are forwards such as dad or mom. Write a program that will accept input from the keyboard and then determine if the entered word is a palindrome. The program should continue as long as there is input OR as long as the user wishes to continue. (java)

The Correct Answer and Explanation is :

Here is a Java program that checks if a word is a palindrome and continues running until the user decides to exit.

Java Program:

import java.util.Scanner;

public class PalindromeChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String choice;

        do {
            System.out.print("Enter a word to check if it is a palindrome: ");
            String word = scanner.nextLine().toLowerCase(); // Convert to lowercase to ignore case sensitivity

            if (isPalindrome(word)) {
                System.out.println(word + " is a palindrome.");
            } else {
                System.out.println(word + " is not a palindrome.");
            }

            System.out.print("Do you want to check another word? (yes/no): ");
            choice = scanner.nextLine().toLowerCase();

        } while (choice.equals("yes"));

        System.out.println("Program terminated.");
        scanner.close();
    }

    public static boolean isPalindrome(String word) {
        int left = 0;
        int right = word.length() - 1;

        while (left < right) {
            if (word.charAt(left) != word.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}

Explanation:

  1. Taking Input:
    The program uses a Scanner object to accept user input. The word entered is converted to lowercase to ensure case insensitivity.
  2. Checking for a Palindrome:
    The isPalindrome method uses two pointers (left and right) to compare characters from both ends of the word. If all corresponding characters match, the word is a palindrome; otherwise, it isn’t.
  3. Loop for Continuous Execution:
    A do-while loop ensures the program keeps running until the user enters “no.”
  4. Time Complexity:
  • Checking if a word is a palindrome runs in O(n) time complexity since it scans half the word.
  • Space complexity is O(1) since only a few extra variables are used.

This program effectively allows continuous checking of palindromes, giving the user control over termination.


Generated Image:

I will now generate an image representing the concept of a palindrome.

Here is the generated image illustrating the concept of a palindrome with a mirrored effect. Let me know if you need any modifications or further explanations!

Scroll to Top