Sevajper Sevajper - 21 days ago 11
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(System.in);
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.
*/
sb.append(revText).reverse().toString();

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

System.out.println(sb.equals(revText));

scan.close();
}


So for instance I enter:

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


Why false ? ;/

Answer

Try

System.out.println(revText.equals(sb.toString()));

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.

Comments