1

So, im at the point of counting the number of nearby mines ASSUMING if the spot chosen had no mines and this is what I came up with:

public static int numNearbyMines( boolean [][]mines, int row, int col) {    

    int nearbyMines = 0;

    if (mines[row - 1][col] == true) {  nearbyMines += 1; }
    if (mines[row - 1][col - 1] == true) {  nearbyMines += 1; }
    if (mines[row -  1][col + 1] == true) {  nearbyMines += 1; }
    if (mines[row][col + 1] == true) {  nearbyMines += 1; }
    if (mines[row][col - 1] == true) {  nearbyMines += 1; }
    if (mines[row + 1][col] == true) {  nearbyMines += 1; }
    if (mines[row + 1][col - 1] == true) {  nearbyMines += 1; }
    if (mines[row + 1][col + 1] == true) {  nearbyMines += 1; }
    return nearbyMines;
}

However, I realized that this method would not work because if I chose a place such as a corner, it would be "reading" outside of the array, hence not working. How would I change this so that even if I picked a corner, it would only read inside the array?

c0der
  • 18,467
  • 6
  • 33
  • 65
Brian Kang
  • 31
  • 2
  • You need to add a check if the address (like [row-1][col]) is a valid one (within bounds). This check is best done in a method. – c0der Nov 02 '17 at 04:07

2 Answers2

2

My solution for this sort of issue is to make a function to read arrays safely. Example:

boolean readMines(int x, int y) {
    if(x >= 0 && x < mines.length && y >= 0 && y < mines[0].length) {
        return mines[x][y];
    }
    return false;
}

This checks to make sure it's safe to read at the indices you give it before reading, and assumes there's no mines in places that can't be read. It should work for what you need.

c0der
  • 18,467
  • 6
  • 33
  • 65
Anonymous Noob
  • 308
  • 1
  • 15
0

You can add a check if the address (like [row-1][col]) is a valid one (within bounds). This check is best done in a method:

boolean isValid(int x, int y) {
    if(x >= 0 && x < mines.length && y >= 0 && y < mines[0].length) {
        return true;
    }
    return false;
}
c0der
  • 18,467
  • 6
  • 33
  • 65