java - 如何修复 java.lang.arrayindexoutofboundsexception : 0?

标签 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(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 所述的两件事(参见第一种情况):

  1. 您没有向主类传递参数。

  2. 数组索引总是从 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/

相关文章:

java - 模式语法异常 : Illegal Repetition when using regex in Java

java - 使用java在C代码中搜索字符串

java - 为什么可以转换不同类型的 map ?

java - 使用父类(super class)静态方法获取子类的实例

java - Web 应用程序如何使用服务器发送的事件获取数据库更新并将更新传播到 Web 客户端?

java - 在一张独特的java图像中收集图像

java - JSR-367 : How to bind a simple json to object and extract data

java - 线程只运行一次

java - 同步方法是否在与 UI 线程 (Android) 不同的线程上运行?

java - Maven 依赖范围。如何理解在哪里可以使用这种依赖?