'How do I check an array's bounds and make sure the code does not error in the game "Go" that I am making in Java
protected void pressedOnSpace(int row, int col) {
if (board[row][col] < board[0][0]) {
canvas.errors = false;
}
if (board[row][col] == GoFrame.WHITE) {
board[row][col] = GoFrame.BLACK;
}
else if (board[row][col] == GoFrame.BLACK) {
board[row][col] = GoFrame.EMPTY;
}
else if (board[row][col] == GoFrame.EMPTY) {
board[row][col] = GoFrame.WHITE;
}
}
I am making the game "Go" for a Java assignment. This is a helper method I'm having issues on. The game is based on arrays and loops. The instructions tell me that I am supposed to implement a bound check and there is a boolean variable "canvas.errors" and if it evaluates to true, a big "X" appears over the board, false is there's no "X". I am supposed to do an array bound check to make sure the "X" does not appear but I am unsure how to go about it because everything I have tried continues to produce an "X" when I click on the board outside of the bounds of the array. I know I am supposed to find all the possible ways the program could error and evaluate those ways to "false" with the variable/function but I cant seem to figure it out. The first "if" statement is what I have as of now for the bound checker after a bunch of tries. Any help would be appreciated as I am a newer coder.
Solution 1:[1]
I think maybe you just need help structuring your code to perform a very common operation referred to as validation, or in plain English, making sure you handle situations where your user submits invalid information. All you want to do is make sure the X and Y values represent a legitimate cell on your goban so that your code doesn't choke later on when it tries to process an invalid value.
protected void pressedOnSpace(int row, int col) {
if (row >= 0 && row < 20) && (col >= 0 && col < 20) {
// insert your logic for changing color
} else {
// insert your logic for drawing a big fat X over the board
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
