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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26602209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 02:54:12  来源:igfitidea点击:

how to fix java.lang.arrayindexoutofboundsexception: 0?

java

提问by user26

I'm a newbie to java. Can anyone pls help me with resolving the error arrayindexoutofboundsexception.

我是新手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();
      }

   }
}

and here is the exception:

这是例外:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Minesweeper.main(Minesweeper.java:5) 

回答by Lrrr

You have to check if there is two args or not, with a code like this:

您必须检查是否有两个 args,代码如下:

if(args.length > 2)

Also I think it is better to change lines like this :

另外我认为最好改变这样的行:

for (int i = 1; i <= M; i++) {
 for (int j = 1; j <= N; j++)

to this:

对此:

for (int i = 0; i <M; i++) {
 for (int j = 0; j < N; j++)

回答by SMA

Two things probably as it says index 0 (see first case for the same):

两件事可能正如它所说的索引 0(参见第一种情况):

  1. You are not passing arguments to your main class.

  2. Array index always start from 0 and not 1. So you might need to change either:

    • your loop to start with 0 and check i < M or N
    • You use array index as i - 1 instead of i.
  1. 您没有将参数传递给主类。

  2. 数组索引总是从 0 开始而不是 1。所以你可能需要更改:

    • 你的循环从 0 开始并检查 i < M 或 N
    • 您使用数组索引作为 i - 1 而不是 i。

Reason you are getting ArrayIndexOutOfBoundException is lets say you have 2 elements in an array. It will be as below:

您收到 ArrayIndexOutOfBoundException 的原因是假设您在数组中有 2 个元素。它将如下所示:

a[0] = 1;
a[1] = 2;

And when you are looping using i = 1; i<=2 you are accessing:

当你使用 i = 1 循环时;i<=2 您正在访问:

a[1] - which is perfect
a[2] - which was not expected?

回答by Abimaran Kugathasan

You have to check the length of the array argsbefore accessing an element. Since you have to access 2nd element in the array, the lengh should be atleast 3. You have to check that like below

您必须args在访问元素之前检查数组的长度。由于您必须访问数组中的第二个元素,因此长度应至少为 3。您必须像下面这样检查

if(args.length > 2) {
  //wrap all code here
}

回答by Levent Divilioglu

(SOLUTION #1)

(解决方案#1)

You have used the command line arguments as below, args[0], args1and args[3] means your class need 3 parameters in order to run correctly however you've provided no parameters thus,

您已使用如下命令行参数,args[0]、args 1和 args[3] 表示您的类需要 3 个参数才能正确运行,但是您没有提供任何参数,因此,

//      int M = Integer.parseInt(args[0]);
//      int N = Integer.parseInt(args[1]);
//      double p = Double.parseDouble(args[2]);

        int M = 2;
        int N = 3;
        double p = 3.99;

Then your code output will be;

那么你的代码输出将是;

* * * 
* * * 

* * * 
* * * 

Your code needs 3 parameters and what I've done above is just assigning those parameters with assignment instead of using the values of args[] array.

您的代码需要 3 个参数,而我上面所做的只是通过赋值来分配这些参数,而不是使用 args[] 数组的值。

(SOLUTION #2)

(解决方案#2)

Instead of changing your code, you can pass 3 command-line arguments which stands for int M, N and double p. To do this in eclipseide;

您可以传递 3 个代表 int M、N 和 double p 的命令行参数,而不是更改您的代码。在eclipseide 中执行此操作;

  1. Right click to your class and select run as -> run configurations ;
  1. 右键单击您的类并选择运行方式 -> 运行配置;

enter image description here

在此处输入图片说明

  1. Select the arguments tab and write your three parameters leaving space in between of them ;
  1. 选择参数选项卡并写下您的三个参数,在它们之间留出空间;

enter image description here

在此处输入图片说明

Now you won't get "ArrayIndexOutOfBoundsException" again, with values 2 4 0.9, the output will be;

现在你不会再得到“ ArrayIndexOutOfBoundsException”,值为2 4 0.9,输出将是;

* * . * 
* . * * 

* * 4 * 
* 4 * * 

(EXPLANATION)

(解释)

There are two problem in your code;

您的代码中有两个问题;

  1. You have the ArrayIndexOutOfBoundsExceptionexception which means your code tries to reach an array value with an exceeding index.

  2. You are using command line arguments but you are not entering any arguments as a parameter. Your main method needs 3 parameters in order to run correctly but with no parameters. args[0], args[1]and args[2]means there is an array names with args[] and you are trying to reach 0th, 1st and 2nd elements of the args[] array. However, if you provide no command-line parameter, you are trying to reach a null value and thus you get;

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at com.stack1.Minesweeper.main(Minesweeper.java:8)

  1. 您有ArrayIndexOutOfBoundsException异常,这意味着您的代码尝试使用超出索引的数组值。

  2. 您正在使用命令行参数,但没有输入任何参数作为参数。您的主要方法需要 3 个参数才能正确运行但没有参数。args[0]args[1]以及args[2]装置有一个阵列名称以ARGS []和你正在试图到达第0,第一和ARGS []数组的第二元素。但是,如果您不提供命令行参数,则您正在尝试达到空值,因此您会得到;

    线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 0 at com.stack1.Minesweeper.main(Minesweeper.java:8)

To make it clear, first I will explain what is ArrayIndexOutOfBoundsException;

为了说清楚,首先我将解释什么是ArrayIndexOutOfBoundsException

ArrayIndexOutOfBoundsExceptionerror occurs when a statement in your code tries to reach an array index where the index is greater than the length of the array. Let me explain this;

当代码中的语句试图到达索引大于数组长度的数组索引时,会发生ArrayIndexOutOfBoundsException错误。让我解释一下;

Assume that you have 2 cars. The color of your first caris red, and the color of your second caris blue. If I ask you that "what's your second car's color" , you will return me the answer as blue. But what is I ask "what's your fifth car's color?" what you will say is "I don't own a fifth car".

假设你有 2 辆车。你的第一辆车的颜色是红色,你的第二辆车的颜色是蓝色。如果我问你“你的第二辆车是什么颜色”,你会回答我蓝色。但我问的是“你的第五辆车的颜色是什么?” 你会说“我没有第五辆车”。

"ArrayIndexOutOfBoundsException" error is the same, in this case, you just return an "ArrayIndexOutOfBoundsException" error because the index 5 is greater than the maximum count of your car indexes, which actually the length of the car array.

ArrayIndexOutOfBoundsException”错误是相同的,在这种情况下,您只需返回“ ArrayIndexOutOfBoundsException”错误,因为索引5大于汽车索引的最大计数,实际上是汽车数组的长度。

String car[] = new String[2];

car[0] = "blue";
car[1] = "red";

To make it clear, let's run the code below;

为了清楚起见,让我们运行下面的代码;

public class CarColorExample
{

    public static void main(String[] args)
    {
        String[] carArray = new String[2];

        carArray[0] = "blue";
        carArray[1] = "red";

        System.out.println("1st car color value: " + carArray[0]);
        System.out.println("2nd car color value: " + carArray[1]);
        System.out.println("3rd car color value: " + carArray[2]);
    }

}

If you try and run the code above, you will get the exception as below;

如果你尝试运行上面的代码,你会得到如下异常;

1st car color value: blue
2nd car color value: red

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at com.stack1.CarColorExample.main(CarColorExample.java:15)

There is the statement "java.lang.ArrayIndexOutOfBoundsException: 2"which actually points to the exceeding index tells you that the carArray does not have a second index.

有语句“java.lang.ArrayIndexOutOfBoundsException: 2”实际上指向超出的索引告诉您carArray 没有第二个索引。

index: 0 --> "blue"
index: 1 --> "red"
index: 2 --> ????

As a second example about the ArrayIndexOutOfBoundsExceptionerror, just check out the code below and run it;

作为关于ArrayIndexOutOfBoundsException错误的第二个示例,只需查看下面的代码并运行它;

    public static void main(String[] args)
    {
        int[] intArray = new int[3];

        intArray[0] = 25;
        intArray[1] = 36;
        intArray[2] = 99;

        //Will work with no error
        for(int i = 0; i < intArray.length; i++)
            System.out.println("index[" + i + "], value:" + intArray[i]);

        //      Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
        //          at com.stack1.ErrorExample2.main(ErrorExample2.java:18)
        //
        //      "ArrayIndexOutOfBoundsException" error will occur for index: 3
        //      The length of the array is 2
        //      index: 0 --> 25
        //      index: 1 --> 36
        //      index: 2 --> 99
        //      There is no third index, That's all
        for(int i = 0; i < intArray.length + 1; i++)
            System.out.println("index[" + i + "], value:" + intArray[i]);
    }

}

Same problem in here, index '3', exceeds the maximum index of the array which is exactly stored in "intArray.length"

同样的问题在这里,索引 '3',超过了精确存储在“intArray.length”中的数组的最大索引