//已知一个数组 arr = {19, 28, 37, 46, 50}; 用程序实现把数组中的元素值交换,
// 交换后的数组 arr = {50, 46, 37, 28, 19}; 并在控制台输出交换后的数组元素。 //方法一
public class ElementReversion {
public static void main(String[] args) {
int[] arr1 = {65, 58, 45, 4, 51, 23, 54, 78, 56};
int[] arr2 = reverse(arr1);
printArray(arr2);
}
public static void printArray(int[] arr1) {
System.out.print("[ ");
for (int i = 0; i < arr1.length; i++) {
if (i == arr1.length - 1) {
System.out.print(arr1);
} else {
System.out.print(arr1 + ", ");
}
}
System.out.print(" ]");
}
public static int[] reverse(int[] arr1) {
int[] arr2 = new int[arr1.length];
for (int i = 0; i < arr1.length; i++) {
arr2 = arr1[arr1.length - 1 - i];
}
return arr2;
}
} //方法二: public class ElementReverse {
public static void main(String[] args) {
int[] arr = {19, 28, 37, 46, 50};
reverse(arr);
print(arr);
} public static void reverse(int[] arr) {
for (int start = 0, end = arr.length - 1; start <= end; start++, end--) {
//变量交换
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
}
public static void print(int[] arr) {
System.out.print("[");
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
System.out.print(arr);
} else {
System.out.print(arr + ", ");
}
}
System.out.print("]");
}
} |