Gaeun Kim
Gaeun Kim

Reputation: 5

Java ArrayIndexOutOfBoundsException (Minesweeper)

I am trying to make a simple minesweeper that plants n*n/3 mines in a n*n board. The mines are marked by *, and blank spaces are marked by 0. (It does not function as a game yet: I'm trying to make the 'answer sheet' of the minesweeper) And please note that I haven't used any methods on purpose.

I am constantly getting an error at the 23rd line:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 15

I have tried for hours to fix this issue, but none seems to work. Can anyone point out what is wrong and how I should fix my code? Thanks.

import java.util.Scanner;
public class Minesweeper {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        char board[][] = new char [n][n]; // makes board of n*n
        int a, b;
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                board[i][j] = '0';
            }
        }
        for (int i = 0; i < n * n / 3; i++) { // '*' is a mine
            a = (int)(Math.random() * (n - 1) + 1.0);
            b = (int)(Math.random() * (n - 1) + 1.0);
            board[a][b] = '*';
        }

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                for (int k = i - 1; k <= i + 1 && k >= 0 && k <= n; k++) {
                    for (int l = j - 1; l <= j + 1 && l >= 0 && l <= n; l++) {
                        if (board[k][l] == '*' && !(k == i && l == j)) {
                            board[i][j] = (char)(Character.getNumericValue(board[i][j]) + 1);
                        }
                    }
                }
            }
        }

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                System.out.println(board[i][j]);
            }
        }
    }

}

Upvotes: 0

Views: 152

Answers (1)

kutschkem
kutschkem

Reputation: 8163

           for (int k = i - 1; k <= i + 1 && k >= 0 && k <= n; k++) {
                for (int l = j - 1; l <= j + 1 && l >= 0 && l <= n; l++) {

It should be k < n and l < n. n is already outside the boundaries.

Also

    for (int i = 0; i < n * n / 3; i++) { // '*' is a mine
        a = (int)(Math.random() * (n - 1) + 1.0);
        b = (int)(Math.random() * (n - 1) + 1.0);
        board[a][b] = '*';
    }

seems wrong, I think it should be

    for (int i = 0; i < n * n / 3; i++) { // '*' is a mine
        a = (int)(Math.random() * n);
        b = (int)(Math.random() * n);
        board[a][b] = '*';
    }

Upvotes: 1

Related Questions