数组的使用

 

 


 1 package array;
 2 
 3 public class ArrayDemo03 {
 4     public static void main(String[] args) {
 5         int[] arrays = {1,2,3,4,5,6};
 6         //打印全部的数组元素
 7         for (int i = 0; i < arrays.length; i++) {
 8             System.out.println(arrays[i]);
 9         }
10         System.out.println("===========================");
11         //计算所有元素的和
12         int sum = 0;
13         for (int i = 0; i < arrays.length; i++) {
14             sum += arrays[i];
15         }
16         System.out.println("总和sum为:" + sum);//21
17         //查找最大元素
18         int max = arrays[0];
19         for (int i = 0; i < arrays.length; i++) {
20             if(arrays[i]>max){
21                 max = arrays[i];
22             }
23         }
24         System.out.println("max="+max);
25     }
26 }

 1 package array;
 2 
 3 public class ArrayDemo04 {
 4     public static void main(String[] args) {
 5         int[] arrays = {1,2,3,4,5,6};
 6 
 7 
 8         //jdk1.5  没有下标
 9         for(int array:arrays){
10             System.out.println(array);
11         }
12 
13         printArray(arrays);//打印数组元素
14         System.out.println();
15         int[] reverse = reverse(arrays);
16         printArray(reverse);
17 
18     }
19     //打印数组元素:
20     public static void printArray(int[] arrays){
21         for (int i = 0; i < arrays.length; i++) {
22             System.out.print(arrays[i]+ " ");
23         }
24     }
25     //反转数组:
26     public static int[] reverse(int[] arrays){
27         int[] result = new int[arrays.length];
28         //反转的操作:
29         for (int i = 0,j = arrays.length-1; i < arrays.length; i++,j--) {
30            result[j] = arrays[i];
31         }
32         return result;
33     }
34 }

 

 
 

 

posted on 2022-07-29 17:16  一枚努力学习的小白  阅读(15)  评论(0编辑  收藏  举报