1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > java中foreach循环遍历二维数组_foreach for循环遍历数组 List

java中foreach循环遍历二维数组_foreach for循环遍历数组 List

时间:2020-01-20 13:59:59

相关推荐

java中foreach循环遍历二维数组_foreach for循环遍历数组 List

[java]代码库/**

* 对整数数组求和

*/

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;

}

/**

* 对整数列表求和

*

* @param nums

* @return

* @throws Exception

*/

public static long getSum(List nums) throws Exception {

if (nums == null) {

throw new Exception("错误的参数输入,不能为null!");

}

long sum = 0;

// 可以跟遍历数组一样的方式遍历列表

for (int x : nums) {

sum += x;

}

return sum;

}

/**

* 求多维数组的平均值

*

* @param nums

* @return

* @throws Exception

*/

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);

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。