1 package com.duan.array;
2
3 public class ArrayDemo03 {
4 public static void main(String[] args) {
5 int[] arrays = {1, 2, 3, 4, 5};
6
7 //打印全部的数组元素
8 for (int i = 0; i < arrays.length; i++) {
9 System.out.println(arrays[i]);
10 }
11 System.out.println("=================");
12 //计算所有元素的和
13 int sum = 0;
14 for (int i = 0; i < arrays.length; i++) {
15 sum += arrays[i];
16 }
17 System.out.println("sum=" + sum);
18 System.out.println("==================");
19 //查找最大元素
20 int max = arrays[0];
21 for (int i = 1; i < arrays.length; i++) {
22 if (arrays[i] > max) {
23 max = arrays[i];
24 }
25 }
26 System.out.println("max=" + max);
27 }
28 }
29 结果:
30 1
31 2
32 3
33 4
34 5
35 =================
36 sum=15
37 ==================
38 max=5
1 package com.duan.array;
2
3 public class ArrayDemo04 {
4 public static void main(String[] args) {
5 int[] arrays = {1, 2, 3, 4, 5};
6 //for (int array : arrays) {
7 // System.out.println(array);
8 //}
9
10 printArray(arrays);
11 int[] reverse = reverse(arrays);
12 System.out.println();
13 printArray(reverse);
14 }
15
16 //打印数组元素
17 public static void printArray(int[] arrays) {
18 for (int i = 0; i < arrays.length; i++) {
19 System.out.print(arrays[i] + " ");
20 }
21 }
22
23 //反转数组
24 public static int[] reverse(int[] arrays) {
25 int[] result = new int[arrays.length];
26
27 //反转的操作
28 for (int i = 0, j = result.length - 1; i < arrays.length; i++, j--) {
29 result[j] = arrays[i];
30 }
31
32 return result;
33 }
34 }
35 结果:
36 1 2 3 4 5
37 5 4 3 2 1