# Array Problem

• June 27th, 2011, 07:13 AM
av8
Array Problem
int [] oddNumbers = {1,3,5,7,9};

oddNumbers[0]=oddNumbers[1];
oddNumbers[1]=oddNumbers[2];
oddNumbers[2]=oddNumbers[3];
oddNumbers[3]=oddNumbers[4];

This would result in : int [] oddNumbers = {3,5,7,9,9} i.e replacing each element in the array( starting at index 0) with the element to its immediate right in the array.

To achieve the result with a for loop I have tried:

for (int i = 0; i <= oddNumbers.length ;i++)
oddNumbers[i] = oddNumbers[i + 1];

I get the following error:
Exception: line 2. java.lang.ArrayIndexOutOfBoundsException

Any thoughts would be gratefully received.
• June 27th, 2011, 07:41 AM
Norm
Re: Array Problem
Quote:

Exception: line 2. java.lang.ArrayIndexOutOfBoundsException
Did the error message give the value of the index that was out of bounds?
Was the value 5?

Remember the maximum index of an array is the array.length -1;
What does your for loop allow the index to increment to?
• June 27th, 2011, 07:56 AM
av8
Re: Array Problem
The value of the index was not given in the error. The penny dropped with the maximum index of the array.length - 1 ,as the first index is 0. Thankyou.

for(int i = 0; i < oddNumbers.length -1;i++)
oddNumbers[i] = oddNumbers[i + 1];

Gives a result :int [] oddNumbers = {9,9,9,9,9}

What have I missed?
• June 27th, 2011, 08:04 AM
Norm
Re: Array Problem
How are you printing out the results?
I get:
System.out.println("oddNumbers=" + Arrays.toString(oddNumbers)); // oddNumbers=[5, 7, 9, 9, 9]
• June 27th, 2011, 08:28 AM
av8
Re: Array Problem
I get the required output.

Thank you Norm.

av8