Im trying to create a minesweeper like simulation when 0 is clear and X is a mine the user inputs the number of mines and using a random generator places it in the 2D array. When i run it the grid print but i get java.lang.ArrayIndexOutOfBoundsException: 4 and not sure how to fix it. I have never worked with 2D arrays before.
import java.util.Scanner;
import java.util.Random;
public class Minesweeper {
private static int count = 0; /* used to count the number of mines */
public static void main ( String [] args) {
int r = 12;
int c = 12;
int ground [][] = new int [r][c]; //2D array 12 x 12
int a = 0; // variable to print 0's as an integer instead of a string
Scanner sc=new Scanner(System.in); // scanner for the user to input number of mines
System.out.print("Enter mines: ");
Random myRandom = new Random();
int N; // N is the variable for the number of mines
N = sc.nextInt(); // scanner to input the number
for (int k = 0; k < ground.length; k++) { // nested loop to print a 12 x 12 grid
for (int j = 0; j < ground.length; j++) {
System.out.print(" " + a + " " ); // prints the 0s
}
System.out.println();
}
while(count <= N) { // loop to count the mine numbers the user chose
/* if count < N, we need to put more mines */
do {
r = myRandom.nextInt(12); // generate the mines in random places
c = myRandom.nextInt(12);
} while(mineOrNot(r, c) == false);
count += 1;// count to place the right amount of mines
}
}
// function to make sure no 2 mines are in the same location
public static boolean mineOrNot(int r, int c) {
int ground [][] = new int [r][c];
// if theres no mines its ok to place one
if(ground[r][c] == 0) {
ground[r][c] = 1; // it is ok, put a mine at here
return true;
}
else
return false;
}
}