1

I am new to java and today I started to work on arrays and I'm lost. I am trying to put some values in an array but I'm getting the error java.lang.ArrayIndexOutOfBoundsException.

Here is what I have done so far.

      int n=6; 
      int[]A= new int [1];

      for(i=0;i<n;i++){
          A[i]=keyboard.nextInt();
      } 
dShringi
  • 1,497
  • 2
  • 22
  • 36
javic0
  • 69
  • 1
  • 2
  • 5

7 Answers7

3

java.lang.ArrayIndexOutOfBoundsException means you are trying to access a array index that doesn't exist.

The problem is that your array is of size one.However, you are going through that loop six times. You can either make n equal to one, or increase the size of your array.

danilo
  • 834
  • 9
  • 25
1

The problem is that the size of your array is of one. You set the size of the array in between those the brackets for the array declaration.

Your for loop goes 6 times. You could change the size of the array to 6.

int n=6;

  int[]A= new int [6];

for(i=0;i<=n;i++)
   {
      A[i]=keyboard.nextInt();

   } 
sudo_coffee
  • 888
  • 1
  • 12
  • 26
danilojara123
  • 368
  • 2
  • 4
  • 12
0

It means kind of what it says. You are trying to access an element outside the bounds of the array you have defined.

your array new int [1]; will only hold one element. I think you meant int [n];

Joel
  • 647
  • 2
  • 11
  • 22
0

You're trying to access memory that you do not have access to. Your array is declared with a size of 1, and you're setting n = 6. So, traversing through the array A, you're trying to access 5 imaginary locations of the array that have not been declared. Thus, array index out of bounds.

What you probably want is this:

  int n=6;

      int[]A= new int [n];

    for(i=0;i<n;i++)
   {
      A[i]=keyboard.nextInt();

   }
sudo_coffee
  • 888
  • 1
  • 12
  • 26
0

Here you have declared size of array as 1 but you are traversing array through 6 times.

in your for loop you should write

for (int i=0; i< A.length; i++ ){

  A[i]=keyboard.nextInt();
}

So in this case, your loop will traversed only once.

Deepak
  • 327
  • 1
  • 7
0

java.lang.ArrayIndexOutOfBoundsException means you are trying to access a array index that doesn't exist. For ex you have a array

        int []array=new int[3];

if you try to access array[4] it will give you ArrayIndexOutOfBoundsException. Bottom line is you will get this exception whenever yo access a array OUT OF ITS BOUND.

:D

Pulkit
  • 3,953
  • 6
  • 31
  • 55
0

Whenever you get an error, always first check out its API. For instance here is the documentation of ArrayIndexOutOfBoundException.

In your code you are creating an array of size 1 by saying new int [1], now when you iterate over the array and check the value for A[1], you're trying to access second element of array, which doesn't even exist as array indexing starts with 0. Hence the Index you are accessing is Out of Bounds.

dShringi
  • 1,497
  • 2
  • 22
  • 36