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:
- Taking Input:
The program uses aScannerobject to accept user input. The word entered is converted to lowercase to ensure case insensitivity. - Checking for a Palindrome:
TheisPalindromemethod uses two pointers (leftandright) to compare characters from both ends of the word. If all corresponding characters match, the word is a palindrome; otherwise, it isn’t. - Loop for Continuous Execution:
Ado-whileloop ensures the program keeps running until the user enters “no.” - 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!