3

I'm just working on a easy easy program with for loop and while loop, and an ArrayIndexOutOfBoundsException occurred.

Here is my code:

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);
     }
  }
}

And here is the error that occurred:

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)
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
maryt
  • 49
  • 4
  • The valid answers are below, but don't be confused if you see 30 lines of garbage text when you print the mary array. For example, see http://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array – OneCricketeer Nov 13 '15 at 13:34

3 Answers3

7

Use

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

mary.length yields 30.

Your array is 30 elements long. The first element is 0 however, making 29 the last element.

Laurens Koppenol
  • 2,946
  • 2
  • 20
  • 33
  • Can you mark it as correct answer if it helped? In my country they banish boys that have below 500 stackoverflow reputation at age 20 – Laurens Koppenol Nov 13 '15 at 14:16
5
int[] mary = new int[30];

Array are indexed starting from 0.

So an int[30] array will have valid indices from 0 to 29

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

in the last iteration you are accessing mary[30] which is out of the bounds of your array.

Fix this by replacing it with

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

With this solution if you change the size of your array you don't have to change the for loop

bznein
  • 908
  • 7
  • 21
1

there is only 30 space in ArrayList(index 0 to 29). index 31 cannot be created.

Object object
  • 872
  • 6
  • 18