Speeed
Speeed

Reputation: 79

How to compare the values with a 2D array elements?

I'm trying to take the user input from scanner and then use said values to compare it to values in a 2D array

public void valid(int tempRow, int tempCol) {
    if (board[tempRow][tempCol] = "W") {
        display();
    } else {
        System.out.println("Move invalid, try again");
        makeMove();
    }
    setPiece(tempRow, tempCol, "W");
    display();
}

This if(board[tempRow][tempCol] = "W"){ returns the error:

incompatable types: java.langString cannot be converted to boolean

Here is the array I'm comparing with:

String[][] board = {
        {"-", "-", "-", "-", "-", "-", "-", "-"},
        {"-", "-", "-", "-", "-", "-", "-", "-"},
        {"-", "-", "-", "-", "-", "-", "-", "-"},
        {"-", "-", "-", "-", "-", "-", "-", "-"},
        {"-", "-", "-", "-", "-", "-", "-", "-"},
        {"-", "-", "-", "-", "-", "-", "-", "-"},
        {"-", "-", "-", "-", "-", "-", "-", "-"},
        {"-", "-", "-", "-", "-", "-", "-", "-"}};

So for example I'm wanting to take the user input for the row and column, say these are row 1 col 1. Then I want to compare both these to the array and see if board[1][1] = "W" if it does then invalid move else place a piece. Any help is appreciated, thanks.

Upvotes: 0

Views: 876

Answers (2)

Shubh
Shubh

Reputation: 1

Instead of

if (board[tempRow][tempCol] = "W")

should be

if (board[tempRow][tempCol] == "W")

Upvotes: 0

k314159
k314159

Reputation: 11100

The statement

if(board[tempRow][tempCol] = "W")

means:

  1. Assign the string "W" to board[tempRow][tempCol]
  2. Test the result to see if it is true.

Which, of course, cannot be done because a string is not a boolean.

You meant to use == instead of =. But that would also be wrong. Use .equals() for string comparisons.

Upvotes: 1

Related Questions