JDK5.0新特性系列---2.新的for循環

import java.util.ArrayList;

import java.util.List;

 

/**

 * 新的for循環,格式爲for(type x:type y)

 * 表示遍歷數組或集合y的元素,把元素值賦給x

 */

public class ForEach {

       /**對整數數組求和*/

       public static long getSum(int[] nums) throws Exception{

              if(nums == null)

                     throw new Exception("錯誤的參數輸入,不能爲null!");

              long sum = 0;

              //依次取得nums元素的值並累加

              for(int x : nums){

                     sum += x;

              }

              return sum;

       }

       /**對整數列表求和*/

       public  static long getSum(List<Integer> nums) throws Exception{

              if(nums == null)

                     throw new Exception("錯誤的參數輸入,不能爲null!");

              long sum = 0;

              //可以與遍歷數組一樣的方式遍歷列表

              for(int x:nums){

                     sum += x;

              }

              return sum;

       }

       /**求多維數組的平均值*/

       public static int getAvg(int[][] nums) throws Exception{

              if(nums == null)

                     throw new Exception("錯誤的參數輸入,不能爲null!");

              long sum = 0;

              long size = 0;

              //對於二維數組,每個數組元素都是一維數組

              for(int[] x : nums){

                     //一維數組中的元素纔是數字

                     for(int y : x){

                            sum += y;

                            size ++;

                     }

              }

              return (int)(sum/size);

       }

      

       public static void main(String[] args)throws Exception{

              int[] nums = {456,23,-739,163,390};

              List<Integer> list_I = new ArrayList<Integer>();

              for(int i = 0; i < 5; i++){

                     list_I.add(nums[i]);

              }

              System.out.println(getSum(nums));

              System.out.println(getSum(list_I));

              int[][] numss = {{1,2,3},{4,5,6},{7,8,9,10}};

              System.out.println(getAvg(numss));

       }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章