Reputation: 199
I am trying to make a program that tests whether a user entered string is a palindrome or not.
This is my code:
import java.util.Scanner;
public class palindrome{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
System.out.println("Enter text");
String inputstr = input.nextLine();
sb.append(inputstr);
if((sb).equals(sb.reverse())){
System.out.println("Palindrome");
}
else{
System.out.println("Not a palindrome");
}
}
}
There are no compile time errors, however no matter what I enter, the output is palindrome. Is there some sort of incompatibility between .equals() and StringBuilder? If so, is there any workaround?
Upvotes: 1
Views: 202
Reputation: 393986
StringBuilder
doesn't override equals
, so you should use String
's equals
instead.
if(sb.toString().equals(sb.reverse().toString()))
P.S even if it did override equals
, your test would always return true, since you are comparing a StringBuilder
instance to itself (reverse
doesn't return a new StringBuilder
instance).
Upvotes: 3