1

Below is my code, goal is to read instructions from a txt file to make java robot preform them. When changing any part of the if statement to != the robot portion works, therefore I have to think that the strings are in some way not equal.

public void interpretGoo() throws AWTException, FileNotFoundException, 
InterruptedException{
    Scanner scanner = new Scanner( new File("instruct.txt") );
    String in;
    String instruct = "";
    while(scanner.hasNextLine()== true){
        in = scanner.nextLine();
        instruct+= in;
    }
    scanner.close();

    String[] instructSet= instruct.split("-");
    System.out.println("String: " + instruct);

    String[] command= new String[10];
    for(int i= 0; i< instructSet.length;i++){
        command= instructSet[i].split(" ");
        System.out.println("Set: " + instructSet[i]);
        System.out.println("Word: " + command[0]);
        if(command[0].trim()== "key"){
            keyboardHandler(command[1].charAt(1));
            Thread.sleep(150);
        }else if(command[0].trim()== "clickL"){
            accuMouse(Integer.parseInt(command[1]),Integer.parseInt(command[2]), 1, false);
        }else if(command[0].trim()== "clickR"){
            accuMouse(Integer.parseInt(command[1]),Integer.parseInt(command[2]), 0, true);
        }else{
            System.out.println("FAIL");
            continue;
        }
    }
}

OUTPUT:

String: clickL 728 1062-clickL 540 382-key h-key e-key l-key l-key o-
Set: clickL 728 1062
Word: clickL
FAIL
Set: clickL 540 382
Word: clickL
FAIL
Set: key h
Word: key
FAIL
Set: key e
Word: key
FAIL
Set: key l
Word: key
FAIL
Set: key l
Word: key
FAIL
Set: key o
Word: key
FAIL

According to the output the strings are identical but fail the checks, any help would be appreciated!

Hopelessdecoy
  • 119
  • 1
  • 2
  • 10
  • Only the contents of the strings are identical. But not the objects themselves. `==` compares for **identity**, not for *content*. Use `equals` to compare for *content*. Also note that comparisons against `true` or `false` are obsolete: `while (foo == true)` is the same as `while (foo)`. – Zabuzard Jul 16 '18 at 18:24

1 Answers1

1

You need to use .equals for string comparison in Java. You’ll find many identical strings do not equal one another if you just use ==. The same goes for most objects. In general it’s safer to use .equals() for equality in Java.

K. Dackow
  • 456
  • 1
  • 3
  • 15
  • That seems counter intuitive to me but it worked. The hardest question is the one you didn't know you didn't know. Thank you! – Hopelessdecoy Jul 16 '18 at 18:34
  • Check this out for clarification: https://stackoverflow.com/questions/7520432/what-is-the-difference-between-vs-equals-in-java – K. Dackow Jul 16 '18 at 18:49