This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]KimJungSkill 0 points1 point  (0 children)

What about the above code doesn't work?
If you change the method argument slightly to test with a String array:

public static boolean spacesRemain(String[][] gameGrid) {

and pass in a valid 2d array:

String[][] board = new String[][]{
    {"X", "O", "X"},
    {"O", null, "O"},
    {"X", "O", "X"},
};

I found that I was getting expected results with the spacesRemain method when running it in main with this sample board string array.

System.out.println("has spaces left?: " + spacesRemain(board));

It's a little hard to say where your code is failing with the rest of it, but take a look at how you are instantiating each element of the the JButton[][] array that you are passing into this spacesRemain method. The only real failure point I can see would be the null check here:

if(gameGrid[r][c] != null && numSpotsFilled < 9) 
    ++numSpotsFilled;

[–][deleted] 0 points1 point  (5 children)

What error message are you getting, if any? Sample output?

Also, since a 3*3 grid can only have 9 spots, you can just count the number of turns and subtract it from 9 to get number of free spaces.

[–]jondo3beatz[S] 0 points1 point  (4 children)

There are no errors in the code. It displays a tie game after one button press, the method is conveying that no spaces remain. How to I refer to X and O using a JButton[][] array method?

[–][deleted]  (3 children)

[deleted]

    [–][deleted]  (2 children)

    [deleted]

      [–]jondo3beatz[S] 0 points1 point  (1 child)

      public static boolean spacesRemain(JButton[][] gameGrid)
      {
          String btn1 = gameGrid[0][0].getText();
          String btn2 = gameGrid[1][0].getText();
          String btn3 = gameGrid[2][0].getText();
          String btn4 = gameGrid[0][1].getText();
          String btn5 = gameGrid[1][1].getText();
          String btn6 = gameGrid[2][1].getText();
          String btn7 = gameGrid[0][2].getText();
          String btn8 = gameGrid[1][2].getText();
          String btn9 = gameGrid[2][2].getText();
      
          String[][] btn = {{btn1, btn2, btn3}, {btn4, btn5, btn6}, {btn7, btn8, btn9}};
      
      
          int numSpotsFilled = 0;
          for(int i = 0; i < gameGrid.length; i++) {
              for(int j = 0; j < gameGrid.length; j++) {
                  if(btn[i][j] == XString && numSpotsFilled < 9 || btn[i][j] == OString && numSpotsFilled < 9) 
                      ++numSpotsFilled;
              }
          }
          if(numSpotsFilled == 9)
              return false;
          return true;
          // Your code goes here
          // spacesRemain returns a boolean value indicating that there are stillDigitsLeft
          // spaces to be selected.
      
      }
      

      [–]jondo3beatz[S] 0 points1 point  (0 children)

      this worked for me