如何修复java.lang.arrayindexoutofboundsexception:0?
发布时间:2020-12-15 05:21:33 所属栏目:Java 来源:网络整理
导读:我是 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
我是
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 in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Minesweeper.main(Minesweeper.java:5) 解决方法
可能有两件事,因为它表示索引0(参见第一个案例):
>您没有将参数传递给主类. >你的循环从0开始并检查i< M或N. 你得到ArrayIndexOutOfBoundException的原因是假设你有一个数组中的2个元素.它将如下: a[0] = 1; a[1] = 2; 当你使用i = 1循环时;我< = 2你正在访问: a[1] - which is perfect a[2] - which was not expected? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |