我正在尝试制作一个简单的扫雷器,在n * n板上种植n * n / 3个地雷。地雷用*标记,空格用0标记。(它还不能作为游戏使用:我正在尝试制作扫雷器的“答题纸”)而且请注意,我还没有使用过有目的的方法。
我在第23行经常出现错误:
线程“主”中的异常java.lang.ArrayIndexOutOfBoundsException:15
我已经尝试了几个小时来解决此问题,但似乎没有任何效果。谁能指出哪里出了问题以及我应该如何修正我的代码?谢谢。
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]);
}
}
}
}
最佳答案
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++) {
它应该是k
也
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 < n * n / 3; i++) { // '*' is a mine
a = (int)(Math.random() * n);
b = (int)(Math.random() * n);
board[a][b] = '*';
}