0

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 ? ;/

Stu
  • 49
  • 7
  • 5
    "I am 99% sure my code is correct yet I can't get a good result." Ummm... if you can't get a good result, then I'm 100% sure your code is incorrect. – Joe C Nov 13 '16 at 19:17

2 Answers2

3

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.

Younes HAJJI
  • 375
  • 3
  • 21
lf215
  • 1,185
  • 7
  • 41
  • 83
1

StringBuilder class does not override equals method from Object class.Hence it's equals method will check if object references are same and if those are same then only it will return true.In case of String class, it overrides equals method from object class and it checks if contents of two strings are equal.

In your code, you are calling equals method on StringBuilder object and as both references are different it is returning false. Convert it to string and then call equals(),

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

Java .equals between String and StringBuilder

Community
  • 1
  • 1
Rohan
  • 3,068
  • 1
  • 20
  • 26