- import java.util.Scanner;
- class Test4 {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("请输入数组长度:");
- int l = sc.nextInt();
- int[] arr = new int[l];
- System.out.println("请输入数组元素,每位空格隔开:");
- for (int i = 0;i <= arr.length-1 ; i ++) {
- arr[i] = sc.nextInt();
- }
- //int[] arr = {1,2,3,4,5,6,7,8};
- reverseArray(arr);
- print(arr);
-
- }
- //数组反转
- public static void reverseArray(int[] arr) {
- int startIndex = 0;
- int endIndex = arr.length-1;
- for (; startIndex <= endIndex;startIndex++,endIndex--) {
- int temp = arr[startIndex];
- arr[startIndex] = arr[endIndex];
- arr[endIndex] = temp;
- }
- }
- //数组打印输出
- public static void print(int[] arr) {
- if (arr == null) {
- System.out.println("null");
- return;
- }
- if (arr.length == 0) {
- System.out.println("[]");
- return;
- }
- System.out.print("[");
- for (int i = 0;i <= arr.length-1 ; i ++) {
- if (i == arr.length-1) {
- System.out.print(arr[i] + "]");
- }else {
- System.out.print(arr[i] + ", ");
- }
- }
- }
- }
复制代码 |