0

So i'm trying to have the user input a string, print it backwards and then compare the new strings to see if it is a palindrome or not... It doesn't seem to be working and i'm not sure why...

public static void main(String[] args) {
    Scanner input = new Scanner (System.in);
    System.out.print("Enter a word: ");
    String word = input.next();
    StringBuilder drow = new StringBuilder(word);
    drow.reverse();
    System.out.println(drow);
    System.out.print(" ");
    String X = drow.toString();
    if (word == X) {
        System.out.println("That word is a palindrome"); 
} else {
    System.out.println("That word is not a palindrome");
}

Thanks for any help to why this isn't working...

user2849489
  • 259
  • 1
  • 2
  • 4

3 Answers3

2

word == X asks if they are literally the same string (i.e. they are two references pointing to the same object in memory), not if they are identically equal (i.e. two different strings that happen to contain the same letters), you want

string.equals(otherString)

The analogy I use with this is identical twins. There are two identical twins. == asks if they are the same person. .equals() asks if they look the same

Richard Tingle
  • 16,906
  • 5
  • 52
  • 77
0

Your comparing references (by using ==) .. Use equalsTo method to compare the string content ..

0

Don't use ==. Use .equals() instead:

if (word.equals(X)) {
    System.out.println("That word is a palindrome"); 
}
Bucket
  • 7,415
  • 9
  • 35
  • 45