Search code examples
javapalindrome

How could I get my program to check if a word is a palindrome irrespective of the case entered by the user


import java.util.Scanner;
public class Pailindrome {
    public static void main(String[] args) {
        Scanner sc1 = new Scanner(System.in);
        System.out.println("Please enter a word");
        String ori = sc1.nextLine();
        isPailindrome(ori);
        if (isPailindrome(ori))
            System.out.println(ori + "is a Pailindrome");
        else
            System.out.println(ori + "is NOT a Pailindrome");
    }
    public static boolean isPailindrome(String ori) {
        int i = 0;
        int j = ori.length() - 1;
        while (i < j) {
            if (ori.charAt(i) != ori.charAt(j)) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
}

The code works perfectly I'm just confused how I will get it to work irrespective of the case inputted by the user. For example aBba is a palindrome but It says it's not in the code I've done. I would like any help if possible thanks.


Solution

  • You can convert all of the letters to lowerCase before you start the processing.

    You can write your own function or use toLowerCase() String function.

    import java.util.Scanner;
    public class Pailindrome {
     public static void main(String[] args) {
      Scanner sc1 = new Scanner(System.in);
      System.out.println("Please enter a word");
      String ori = sc1.nextLine();
      ori = ori.toLowerCase();
      isPailindrome(ori);
      if (isPailindrome(ori))
     }
     System.out.println(ori + "is a Pailindrome");
    } else {
     System.out.println(ori + "is NOT a Pailindrome");
    }
    }
    public static boolean isPailindrome(String ori) {
     int i = 0;
     int j = ori.length() - 1;
     while (i < j) {
      if (ori.charAt(i) != ori.charAt(j)) {
       return false;
      }
      i++;
      j--;
     }
     return true;
    }