0

I am relatively new to coding in general and have run into an issue, I've looked everywhere for help but I cant find this issue. It would be greatly appreciated if someone could tell me why the string "s" doesn't ever equal the string "temp" even if I type the correct number in.

String s = null;
        do{
            s = (String) JOptionPane.showInputDialog(null, "Select a card to check for (Jacks = 11, Queens = 12, Kings = 13)", "Player's Turn", JOptionPane.PLAIN_MESSAGE, null, null, "Pick a card");

            System.out.println(s);
            for(int x = 0; x < PlayerCards.size(); x++){
                String temp = PlayerCards.get(x).getFace();
                if(s == temp){
                    playerhas = true;
                }
            }
            if(s == null || playerhas != true){
                JOptionPane.showMessageDialog(null, "Please pick a card you have.", "Error", JOptionPane.INFORMATION_MESSAGE);
            }
        }while(s == null || playerhas != true);

4 Answers4

1

Strings work like objects in Java.

If you do stringA == stringB this will always return false since stringA and stringB are different objects.

Comparing strings needs to be done using stringA.equals(stringB) and this should return true (if the values match).

Chris
  • 171
  • 1
  • 7
0

Chris 7 you're right that strings are objects but new compilers do some optimizations on those strings and it could happen that stringA == stringB are equal but it's not promised. So you should always use the string comparison functions (String.equals or String.equalsIgnoreCase).

By the way you can optimize your code. Use functions that implement only one feature and not more... e.g. externalize your function that checks if one has the card or not:

boolean playerHas(String s) { for (PlayerCard card : playerCards) { ... } return false; }
m3ns1
  • 61
  • 5
0

The

==

operator compares objects, while the

.equals

function compares object values.

String foo = "loremipsum";
String bar = "loremipsum";
System.out.println(foo == bar);
System.out.println(foo.equals(bar));
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

this ==compare bits, it works with primitive variable because when you declare a primitive variable it saves its value in bits, but when you declare a reference variable it only works if two reference are the same.

See this example:

String object1 = new String("hola");
String object2 = object1;
System.out.print(object1==object2);

This will return true because object2 have the same bits that point to the same object on heap, because they were copied when i said:object2 = object1

So if you want to compare objects by value instead by reference you have to use: equals() method.

Luis Pena
  • 4,132
  • 2
  • 15
  • 23