Sevajper Sevajper - 1 year ago 77
Java Question

Palindrome java error

I have a problem in Java. I am making a program to check if a given text is Palindrome or not. I am 99% sure my code is correct yet I can't get a good result. Here is the code.

public static void main(String[] args) {
Scanner scan = new Scanner(;
StringBuilder sb = new StringBuilder();

System.out.print("Enter a line of text to check if palindrome: ");
String text = scan.nextLine();
String revText = text.replaceAll("[^A-Za-z]", "").toLowerCase().trim(); /*
* Using regex here... everything that is not
* (^) from A-Z (capital) to a-z replace with
* ("") in revText.

System.out.println("Reversed: " + sb);
System.out.println("Normal: " + revText);



So for instance I enter:

Enter a line of text to check if palindrome: Anna2023
Reversed: anna
Normal: anna

Why false ? ;/

Answer Source



sb is not equal to the string because it is not a String. It is a container for building a string. The reason printing sb shows the String is that System.out.println will call toString on whatever is given to it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download