Home » Java » java – reversing the order of elements in Array-Exceptionshub

java – reversing the order of elements in Array-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

i’m currently stuck on an assignment where I have to reverse the order of the elements in my Array.
But the problem is that I only get the 10 10 times and not 10 9 8…

package JavaSection4;

public class Assignment4Nr2 {

    public static void main(String[] args) {        

        int[] ranNum = new int[10];

        ranNum[0] = 1;
        ranNum[1] = 2;
        ranNum[2] = 3;
        ranNum[3] = 4;
        ranNum[4] = 5;
        ranNum[5] = 6;
        ranNum[6] = 7;
        ranNum[7] = 8;
        ranNum[8] = 9;
        ranNum[9] = 10;     

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

            int l = 0;

            l = ranNum.length - 1;

            System.out.println(ranNum[l]);      
        }       
    }
}
How to&Answers:
public class ReverseArray {  
public static void main(String[] args) {  
    //Initialize array  
    int [] arr = new int [] {1, 2, 3, 4, 5};  
    System.out.println("Original array: ");  
    for (int i = 0; i < arr.length; i++) {  
        System.out.print(arr[i] + " ");  
    }  
    System.out.println();  
    System.out.println("Array in reverse order: ");  
    //Loop through the array in reverse order  
    for (int i = arr.length-1; i >= 0; i--) {  
        System.out.print(arr[i] + " ");  
    }  
}  

}

should do the trick.

Answer:

You’re not reversing the order, You’re just trying to read it from the end.

Reversing the order would be

Integer[] integers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
ArrayUtils.reverse(integers);

By using the appripriate tools (in this case apache-commons). Finding out how it’s done is easy by checking the tools source code:

public static void reverse(Object[] array) {
    if (array == null) {
        return;
    }
    int i = 0;
    int j = array.length - 1;
    Object tmp;
    while (j > i) {
        tmp = array[j];
        array[j] = array[i];
        array[i] = tmp;
        j--;
        i++;
    }
}