-2

I'm trying to identify an object based on user input and have no idea why it's not working...

userInput is just a scanner, and allGames is an arraylist of a bunch of 'Game' classes with IDs like S01, S02 etc.

Game gameToChange = null;
for (Game g : allGames){
        System.out.println(g.getId());
}
String gameInput = userInput.nextLine();
    System.out.println(gameInput);
    for (Game g : allGames){
        if (gameInput == g.getId()){
            System.out.println("Found it");
            gameToChange =g;
        }
    }

The Game class:

public abstract class Game {

    private String identifier;

    public Game(String id){
        identifier = id;
    }

    public String getId(){
        return this.identifier;
    }
}

I have the printout for "found it" just so I can check when it's working...but no matter when I enter the correct string, one that matches one which is already printed out, it never equals it.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Jordan Andrews
  • 163
  • 3
  • 16
  • `String` comparison in Java is done using `String@equals` not `==`, the difference between comparing the contents of the `String` and the memory location of two different instances of `String`... – MadProgrammer Sep 22 '14 at 06:11
  • 2
    Duplicate of http://stackoverflow.com/q/513832/3680684 – herrlock Sep 22 '14 at 06:11

2 Answers2

1

Since these two gameInput and g.getId() are type Strings.

You should use equals() instead of ==

equals() compare the content each variable

== compare the reference if they are looking at the same thing or not

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
1

Change

if (gameInput == g.getId()){

to

if (gameInput != null && gameInput.equals(g.getId())){
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199