on my last project for my intro to coding course and I'm running into a bit of an issue when I try to print out/modify/access elements in a 2D array. To make a long story short, I'm building a connect four game and have been given some complete and some incomplete classes to put together to generate the game.
One of the methods under the column class (which contains the second array of values char, also called column), is called get and the code is as follows:
public char get(int row) {
row = height;
if(row < 7 && row > 0) {
System.out.println(column[row]);
return column[row];
} else {
char invalid = ' ';
return invalid;
}
}
Currently the game prompts the user for a name to assign to a Player class, then displays the game before also prompting the user to enter a column number to add their token (X) to the board, adding it automatically to the bottom of the column. The code for the makeMove method is:
public boolean makeMove(int column, char token) {
boolean success = false;
char columnConverter = (char)column;
if(column > 7 && column < 1) {
System.out.println("Sorry, that's not a valid column!");
success = false;
} else {
board[column].put(token);
System.out.println(board[column].put(token));
success = true;
}
return success;
}
And the code to actually place the token is:
public boolean put(char token) {
if (height <= MAX_HEIGHT) {
column[height] = token;
height++;
return true;
} else {
return false;
}
}
When I call the display method for the game, the output (and code at the top) is as follows:
public void display() {
System.out.println("1 2 3 4 5 6 7");
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < NUM_ROWS; j++)
System.out.println("[" + board[i].get(j) + "]");
}
System.out.println("1 2 3 4 5 6 7");
}
OUTPUT:
Welcome to Nibble Nabble! What's your name?
Alex
1 2 3 4 5 6 7
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
[ ]
1 2 3 4 5 6 7
Alex > 0
true
Because of this, I'm fairly certain the issue is with the get method, but am completely lost as to what needs to be fixed. I'm also getting the ArrayIndexOutOfBoundsException if I enter any value higher than 0 for the user prompt.