Write a method called printPalindrome that accepts a Scanner for the console as a parameter, and prompts the user to enter one or more words and prints whether the entered String is a palindrome (i.e., reads the same forwards as it does backwards, like "abba" or "racecar").
For an added challenge, make the code case-insensitive, so that words like “Abba” and “Madam” will be considered palindromes.
import java.util.Scanner;
public class PalindromeCheck {
// below method check whether the string is palindrom or not and also return true if
// it is palindrome.
public static boolean printPalindrome() {
System.out.print("enter a string: ");
// takes inpur from the console
Scanner input = new Scanner(System.in);
String str = input.nextLine();
// make it lowercase make the functions independent of case
String var = str.toLowerCase();
int i = 0;
int j = str.length() - 1;
boolean flag = false;
// this loop continours as long as i < j
while(i < j) {
if(var.charAt(i) != var.charAt(j)) {
System.out.println("the string is not a palindrome");
return flag;
}
i++;
j--;
}
System.out.println("the string is a palindrome");
input.close();
flag = true;
return flag;
}
public static void main(String[] args) {
PalindromeCheck.printPalindrome();
}
}
Output:
enter a string: madam
the string is a palindrome