How to use charAt() properly when I am checking if a word is palindrome in Java?

Viewed 106

For simple words as "madam", "madama" etc., the code is working but for longer Strings like "babzsákfotelben sok a bab" returns wrong answer.

Scanner sc = new Scanner(System.in);

        String A = sc.nextLine();

        String myString = A.toLowerCase().replaceAll("\\s", "");
        int i = 0;
        int j = myString.length() - 1;

        while (i < j) {

            if (myString.charAt(i) != myString.charAt(j)) {

                System.out.println("No");
                break;

            }

            i++;
            j--;

            System.out.println("Yes");
            break;
        }
    }
}
2 Answers

Problem in your current code is that your loop only executes once because after incrementing i and decrementing j, you print "Yes" and break out of the loop.

What you should do is declare a boolean variable that is initialized with the value true. Inside the loop, in any iteration, if the if condition evaluates to true, set that boolean variable's value to false and break out of the loop.

After the loop ends, check if the value of the boolean variable is still true. If it is, then string is a palindrome, otherwise its not.

int i = 0;
int j = myString.length() - 1;
boolean isPalindrome = true;

while (i < j) {
    if (myString.charAt(i) != myString.charAt(j)) {
        isPalindrome = false;
        break;
    }

    i++;
    j--;
}
    
if (isPalindrome) {
   System.out.println("Yes");
} else {
   System.out.println("No");
}

**What you can do is instead of using a while loop, you can use for loop, and instead of a string, you can use StringBuilder. Here's how it goes:

**

public class Palindrome {
public static void main(String[] args) {
    //Creating an instance of scanner class
    Scanner scan = new Scanner(System.in);
    //Creating an instance of StringBuilder class
    StringBuilder str = new StringBuilder();
    //Asking for input
    System.out.println("Please Enter the Word: ");
    //Getting Input
    String word = scan.next();

    /*
     *
     * Palindrome Check
     *
     */

    for (int i = word.length() - 1; i >= 0; i--) {
        str.append(word.charAt(i));
    }
    if (word.equalsIgnoreCase(String.valueOf(str))) {
        System.out.println("Yes");
    } else {
        System.out.println("No");
    }

}

}

Related