-1

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]);      
        }       
    }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
IyadELwy
  • 15
  • 6
  • `l = ranNum.length - 1 - i;` or change the loop to start at the end and decrement – Scary Wombat Feb 17 '20 at 05:29
  • `l` is always the same, `ranNum.length - 1`. And this is not reversing the order, just printing it from the end to start. By the way to iterate from the end use `for(int i = ranNum.length - 1; i >= 0; i--)` – Guy Feb 17 '20 at 05:29

2 Answers2

1

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++;
    }
}
Nicktar
  • 5,548
  • 1
  • 28
  • 43
0
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.

Dan
  • 79
  • 4
  • Why should this "do the trick"? Please read [answer] and [edit] accordingly. Always remember you are not only answering to the OP, but also to any future readers of this post. Thus, please add some explanation to this code. – Adriaan May 06 '20 at 10:54