I have an assignment to create a class in which I create an array of size 10, called source, and assign random integers in the range 0-10 to all indexes in it, and then call a method that creates a new array in reverse order. I tried the code below:
public class Exercise7_4 {
// reverse array method
public static int[] reverseArray(int[] arr) {
int[] reverse = new int[arr.length];
for (int i = 0; i < reverse.length - 1; i++) {
reverse[i] = arr[arr.length - 1 - i];
}
return reverse;
}
// print array in ascending order
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
System.out.printf("%d\t", arr[i]);
}
System.out.println();
}
public static void main(String[] args) {
int[] source = new int[10];
for (int i = 0; i < source.length - 1; i++) {
source[i] = (int) (Math.random() * 10 + 1);
}
int[] reverse = reverseArray(source);
printArray(source);
printArray(reverse);
}
}
The problem is that the output i get looks like this:
7 1 3 7 10 9 6 2 6
0 6 2 6 9 10 7 3 1
meaning, the reverseArray method doesn't work properly on reverse[0] for some reason.
I would like to know why this is happening and how I can fix it. Thanks in Advance!
0toarr.length - 2andreverse.length - 2. Change your loops to resemblefor (int i = 0; i < reverse.length; i++)instead offor (int i = 0; i < reverse.length - 1; i++)