Skip to content
Advertisement

Creating a New Reverse Java Array

CodingBat > Java > Array-1 > reverse3:

Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}.

public int[] reverse3(int[] nums) {
    int[] values = new int[3];
    for (int i = 0; i <= nums.length - 1; i++) {
        for (int j = nums.length-1; j >= 0; j--) {
            values[i] = nums[j];
        }
    }
    return values;
}

I can’t get this to work properly, usually the last int in the array, becomes every single int in the new array

Advertisement

Answer

You don’t want a two-level loop. Just have one loop:

for(int i = 0, j = nums.length - 1; i < nums.length; i++,j--) {
    values[i] = nums[j];
}

or, alternately, just don’t track j sepearately, and do this:

for(int i = 0; i < nums.length; i++) {
    values[i] = nums[nums.length - 1 - i];
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement