Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

1. ## 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.

2. ## Re: Array Problem

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?

3. ## 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?

4. ## 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]

5. ## Re: Array Problem

I get the required output.

Thank you Norm.

av8