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?
StringBuilder
doesn't override equals
, so you should use String
's equals
instead.
if(sb.toString().equals(sb.reverse().toString()))
PS 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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.