如何解决此代码中的ArrayIndexOutOfBoundsException?

mar*_*ryt 3 java arrays for-loop while-loop

我正在开发一个简单易用的程序,使用for循环和while循环,并且ArrayIndexOutOfBoundsException发生了.

这是我的代码:

public class ForWhileLoops
{
   public static void main(String[] args)
   {
     int[] mary = new int[30];

     for(int a = 0; a < 31; a++)
     {
      mary[a]= a*3;
     }
     for(int b = 0; b < 31; b++)
     {
       System.out.println(mary);
     }
     int c = 0;
     while(c < 31)
     {
       c++;
       System.out.println(c);
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

这是发生的错误:

java.lang.ArrayIndexOutOfBoundsException: 30
    at ForWhileLoops.main(ForWhileLoops.java:9)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Run Code Online (Sandbox Code Playgroud)

Lau*_*nol 7

使用

for int(a = 0; a < mary.length; a++) { 
    ... 
}
Run Code Online (Sandbox Code Playgroud)

mary.length产生30.

你的数组长30个元素.然而,第一个元素是0,使29成为最后一个元素.


bzn*_*ein 5

int[] mary = new int[30];
Run Code Online (Sandbox Code Playgroud)

数组从索引开始0.

因此,一个int[30]阵列将具有有效索引029

for(int a = 0; a < 31; a++)

在最后一次迭代中,您正在访问mary[30]哪个超出了数组的范围.

通过替换它来解决这个问题

for(int a = 0; a <mary.length; a++)

使用此解决方案,如果更改阵列的大小,则无需更改for循环