0

I have an else-if loop that compares a variable to a String letter, but it does not seem to detect any matches. My code is as follows:

public static void useMove(String move){
    System.out.println(move);
    System.out.println(move.getClass().getName());
    if(move == "N"){
        GLObject.MOVE('N');
    }
    else if(move == "E"){
        GLObject.MOVE('E');
    }
    else if(move == "S"){
        System.out.println("GOT HERE");
        GLObject.MOVE('S');
    }
    else if(move == "W"){
        GLObject.MOVE('W');
    }
    else if(move == "HELLO"){
        GLObject.HELLO();
    }
    else if(move == "PICKUP"){
        GLObject.PICKUP();
    }
    else if(move == "LOOK"){
        GLObject.LOOK();
    }
    else if(move == "QUIT"){
        GLObject.QUIT();
    }
}

If I enter the value of move as the String "S" it does not detect that move is equal to "S". So the output I get is:

S
java.lang.String

Can anyone advise as to what the problem is?

Thanks very much.

twlkyao
  • 14,302
  • 7
  • 27
  • 44
user3120023
  • 197
  • 3
  • 6
  • 16

4 Answers4

1

In Java, you should preform String comparison using the equals method, so in your case, you have to use:

if(move.equals("PICKUP")){
// do something
}

// the comparisons for the other cases work the same way
fedorSmirnov
  • 701
  • 3
  • 9
  • 19
0

for string comparison you could use equals() or equalsIgnoreCase() function. But otherwise you could use character data type to make a comparison with equalitty operator.

royal52
  • 29
  • 4
0

When you're working with String you should use the equals() method to compare its value instead of the bits it contains.

String hi = "hi";
String hi2 = "hi";

if(hi.equals(hi2)){
System.out.println("true"); 
}
Luis Pena
  • 4,132
  • 2
  • 15
  • 23
0

== operator in case of string compare address of two strings.You should use move.equals("E") to compare two strings.

Devavrata
  • 1,785
  • 17
  • 30