如何修复java.lang.arrayindexoutofboundsexception:0? [英] how to fix java.lang.arrayindexoutofboundsexception: 0?
问题描述
我是 java
的新手。任何人都可以帮我解决错误 arrayindexoutofboundsexception
。
I'm a newbie to java
. Can anyone pls help me with resolving the error 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 in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Minesweeper.main(Minesweeper.java:5)
推荐答案
可能有两件事,因为它表示索引0(见第一个案例):
Two things probably as it says index 0 (see first case for the same):
-
您没有将参数传递给您的主类。
You are not passing arguments to your main class.
数组索引始终从0开始而不是1.因此您可能需要更改:
Array index always start from 0 and not 1. So you might need to change either:
- 你的循环从0开始并检查i< M或N
- 您使用数组索引作为i - 1而不是i。
您获得ArrayIndexOutOfBoundException的原因是假设您在数组中有2个元素。它将如下所示:
Reason you are getting ArrayIndexOutOfBoundException is lets say you have 2 elements in an array. It will be as below:
a[0] = 1;
a[1] = 2;
当你使用i = 1循环时; i< = 2您正在访问:
And when you are looping using i = 1; i<=2 you are accessing:
a[1] - which is perfect
a[2] - which was not expected?
这篇关于如何修复java.lang.arrayindexoutofboundsexception:0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!