-1

I want to reverse an array, so when i input

1 4 5 6

i want the program to return

6 5 4 1

This is what i have coded but i keep getting a arrayIndexOutOfBoundException error.

import java.io.*;
import java.util.*;

public class Oef9
{

    public int[] array_oef9 (int[] array1){
        int lengte=array1.length;
        int[] array= new int[lengte];

        for (int i=0; i<lengte;i++ ){
            array[lengte]=array1[i];
            lengte=lengte-1;
        }
        return array;

    }
}
TinaXx
  • 33
  • 2
  • 10
  • You need to give your length an extra space; – Ya Wang Jan 17 '16 at 23:10
  • Don't update `lengte` in the loop, since it is also using in the loop condition, otherwise `i` and `lengte` will "meet" when you're halfway through the iteration. – Andreas Jan 17 '16 at 23:21
  • 4
    Possible duplicate of [How do I reverse an int array in Java?](http://stackoverflow.com/questions/2137755/how-do-i-reverse-an-int-array-in-java) – ben75 Jan 17 '16 at 23:47

4 Answers4

1

Reason why it does that is because you are using lengte as the length of the array. The first index of your new array should be 1 less then the length. lengte would be 4 and the last index would be 3.

public class Oef9{

public int[] array_oef9 (int[] array1){
    int lengte=array1.length;
    int[] array= new int[lengte];

    for (int i=0; i<array1.length;i++ ){
        array[--lengte]=array1[i];
    }
    return array;
} 
}

Hope this helps you Tina. Let me know if you need any more clarification :)

deltashade
  • 386
  • 1
  • 13
1
   for (int i=0; i<lengte;i++ ){
        array[lengte - 1 - i]=array1[i];

    }

Try this instead of your current loop. You are currently passing in the length as an index, but the greatest possible index is length - 1.

Microshark
  • 23
  • 6
1

The last element in the array is at the length-1 position.

Better try to iterate from end to start, like this:

int j = 0;
for(int i = lengte - 1, i >= 0, i--) {
    array[j] = array1[i];
    j++;
}
0

If you don't need to use an array

Collections.reverse(List)

will do nicely.

Or, you could use the following

public static void main(String[] args) {
    int[] array = { 2,9,5,6,3 };


    int[] reversed = new int[array.length];

    for (int i = array.length; i > 0; i--) {
        reversed[reversed.length - i] = array[i-1];
    }

    for (int j : reversed) {
        System.out.print(j + ",");
    }


}
kbz
  • 984
  • 2
  • 12
  • 30