我是 java
的新手。谁能帮我解决错误 arrayindexoutofboundsexception
。
public class Minesweeper {
public static void main(String[] args) {
int M = Integer.parseInt(args[0]);
int N = Integer.parseInt(args[1]);
double p = Double.parseDouble(args[2]);
// game grid is [1..M][1..N], border is used to handle boundary cases
boolean[][] bombs = new boolean[M+2][N+2];
for (int i = 1; i <= M; i++)
for (int j = 1; j <= N; j++)
bombs[i][j] = (Math.random() < p);
// print game
for (int i = 1; i <= M; i++) {
for (int j = 1; j <= N; j++)
if (bombs[i][j]) System.out.print("* ");
else System.out.print(". ");
System.out.println();
}
// sol[i][j] = # bombs adjacent to cell (i, j)
int[][] sol = new int[M+2][N+2];
for (int i = 1; i <= M; i++)
for (int j = 1; j <= N; j++)
// (ii, jj) indexes neighboring cells
for (int ii = i - 1; ii <= i + 1; ii++)
for (int jj = j - 1; jj <= j + 1; jj++)
if (bombs[ii][jj]) sol[i][j]++;
// print solution
System.out.println();
for (int i = 1; i <= M; i++) {
for (int j = 1; j <= N; j++)
if (bombs[i][j]) System.out.print("* ");
else System.out.print(sol[i][j] + " ");
System.out.println();
}
}
}
这里是异常(exception):
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Minesweeper.main(Minesweeper.java:5)
最佳答案
可能如索引 0 所述的两件事(参见第一种情况):
您没有向主类传递参数。
数组索引总是从 0 而不是 1 开始。因此您可能需要更改其中之一:
- 你的循环从 0 开始并检查 i < M 或 N
- 您使用数组索引作为 i - 1 而不是 i。
你得到 ArrayIndexOutOfBoundException 的原因是假设你在一个数组中有 2 个元素。它将如下所示:
a[0] = 1;
a[1] = 2;
当你循环使用 i = 1; i<=2 您正在访问:
a[1] - which is perfect
a[2] - which was not expected?
关于java - 如何修复 java.lang.arrayindexoutofboundsexception : 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26602209/