?? foreach.java
字號:
package book.j2se5;
import java.util.ArrayList;
import java.util.List;
/**
* 新的for循環(huán)。格式為for(type x: type y);
* 表示依次遍歷數(shù)組或集合y的元素,把元素值賦給x,
* 注意,
* (1)只能遍歷的取數(shù)組元素,不能修改數(shù)組的元素,即修改x的值對數(shù)組沒有影響;
* (2)遍歷是依次,不能跳著遍歷。
*/
public class ForEach {
/**
* 對整數(shù)數(shù)組求和
*/
public static long getSum(int[] nums) throws Exception{
if (nums == null){
throw new Exception("錯誤的參數(shù)輸入,不能為null!");
}
long sum = 0;
// 依次取得nums元素的值并累加
for (int x : nums){
sum += x;
}
return sum;
}
/**
* 對整數(shù)列表求和
* @param nums
* @return
* @throws Exception
*/
public static long getSum(List<Integer> nums) throws Exception{
if (nums == null){
throw new Exception("錯誤的參數(shù)輸入,不能為null!");
}
long sum = 0;
// 可以跟遍歷數(shù)組一樣的方式遍歷列表
for (int x : nums){
sum += x;
}
return sum;
}
/**
* 求多維數(shù)組的平均值
* @param nums
* @return
* @throws Exception
*/
public static int getAvg(int[][] nums) throws Exception{
if (nums == null){
throw new Exception("錯誤的參數(shù)輸入,不能為null!");
}
long sum = 0;
long size = 0;
// 對于二維數(shù)組,每個數(shù)組元素都是一維數(shù)組
for (int[] x : nums){
// 一維數(shù)組中的元素才是數(shù)字
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));
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -