Write a java program to accept a string from user and check whether it is palindrome.
In this tutorial we are going to learn how we can write a java program to accept a string from user and check whether it is palindrome or not.
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
if (isPalindrome(input)) {
System.out.println(input + " is a palindrome.");
} else {
System.out.println(input + " is not a palindrome.");
}
}
public static boolean isPalindrome(String str) {
// Remove spaces and convert the string to lowercase
String cleanStr = str.replaceAll("\\s", "").toLowerCase();
// Compare the original string with its reverse
StringBuilder reversedStr = new StringBuilder(cleanStr).reverse();
return cleanStr.equals(reversedStr.toString());
}
}
OutPut :
Comments
Post a Comment