Search code examples
javatic-tac-toe

Java Tic Tac Toe: convert string to check for value in 2d array


I'm creating a simple tic tac toe game. I initialized my 3x3 board using a single space character.

private char[][] board;
private char player; // 'X' or 'O'

public TicTacToe() {
 for(int i = 0; i < 3; i++)
   {
     for(int j = 0; j <3; j++)
     {
       board[i][j] = ' ';
     }
   }
 player = 'X';
 }

I ask the user to enter the coordinates as shown below:

   1  2  3
A |  |  |  |
B |  |  |  |
C |  |  |  |

so if X enters B2 and O enters A3, the board will look like this:

   1  2  3
A |  |  |O |
B |  | X|  |
C |  |  |  |

Right now, I'm trying to code a method that checks to see if a current player's move is valid.

Question: How do I convert the user string input (A=1,B=2,C=3) so that I can see if board[x][y] contains a ' ' character?


Solution

  • You can use String.charAt(int) to get a character from any point in the string. Note that, like arrays, the first character in a string is index 0, not 1.

    You can then convert these to indices, like so:

    input = input.toUpperCase(); // Makes code work for all cases
    int x = input.charAt(0) - 'A';
    int y = input.charAt(1) - '1';
    char currentValue = board[x][y];
    

    After that, currentValue will contain the value currently on the game board at that location.