35 输入数组,最大的与第一个元素交换,最小的与最后一个元素交
2023-10-23 本文已影响0人
北极的大企鹅
题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组
1 public class _035ExchangeArray {
2
3 public static void main(String[] args) {
4 exchangeArray();
5 }
6
7 private static void exchangeArray() {
8 final int N = 8;
9
10 int[] a = new int[N];
11
12 Scanner scanner = new Scanner(System.in);
13
14 System.out.println("请输入8个整数 :");
15
16 for (int i = 0; i < N; i++) {
17 a[i] = scanner.nextInt();
18 }
19
20 // 获得输入的八个数字
21 System.out.println("你输入的数组为:");
22 for (int i = 0; i < N; i++) {
23 System.out.print(a[i] + " ");
24 }
25
26 // 输出输入的数组
27 int max = 0, min = 0;
28 for (int j = 0; j < N; j++) {
29 if (a[j] > a[max]) {
30 max = j;
31 }
32 }
33 int temp = a[0];
34 a[0] = a[max];
35 a[max] = temp;
36
37 for (int j = 0; j < N; j++) {
38 // 找出最大数和最小数的下标
39 if (a[j] < min) {
40 min = j;
41 }
42 }
43
44 int temp1 = a[N - 1];
45 a[N - 1] = a[min];
46 a[N - 1] = temp1;
47
48 System.out.println("\n交换后的数组为:");
49 for (int k = 0; k < N; k++) {
50 System.out.print(a[k] + " ");
51 }
52 }
53 }