0

I am not sure why but when I get a string from the user, I cannot compare it in an if statement but when I try to print it, it works fine.

Part of my code:

         Scanner in = new Scanner(System.in);
         while (true) {
             String userInput;
             int rowInput, colInput;
             printBoard(board);
             System.out.print("Move: ");

             userInput = in.next();

             // shift board right on a row
             if (userInput == "r") {
                 System.out.print("row #: \r");
                 rowInput = in.nextInt();
                 moveRight(--rowInput, board);
             }

Does anyone know why this isn't working as expected?

QQPrinti
  • 61
  • 1
  • 9

2 Answers2

0

You an try this:

if (userInput.equals("r"))

== is used to compare the address and equals is used to compare contents.

Bahramdun Adil
  • 5,907
  • 7
  • 35
  • 68
0

I should be using equals instead of ==.

So it would lead to:

...

if (userInput.equals("r"))

...
thyago stall
  • 1,654
  • 3
  • 16
  • 30