我正在尝试反转一个 int 值数组。它似乎没有正确地做到这一点。你会注意到我以不同的方式打印,比如Array.toString()
和使用println
.
原始数组打印:
1 4 9 16 9
我需要它来打印:
9 16 9 4 1
这是我的代码:
import java.util.Arrays;
public class ReverseArray {
public static void main(String[] args) {
int[] data = { 1, 4, 9, 16, 9 };
reverseArray(data);
int[] dataR = reverseArray(data);
System.out.println("Reveresed data " + Arrays.toString(dataR));
}
public static int[] reverseArray(int[] data) { // returns the reverse of the
// array data
// int [] data = new int[5];
int[] reversedData = new int[data.length];
data[0] = 1;
data[1] = 4;
data[2] = 9;
data[3] = 16;
data[4] = 9;
System.out.println(Arrays.toString(data));
for (int i = 0; i < data.length - 1; i++) {
System.out.println("Original Array: " + data[i]);
}
int reveresedData[] = data;
for (int i = 0; i < reveresedData.length - 1; i++) {
reversedData[(data.length - 1) - i] = data[i];
System.out.println(reveresedData[i]);
}
return reveresedData;
}
}