2.新的for循环
来源:互联网 发布:文怡的服装淘宝店网址 编辑:程序博客网 时间:2024/05/29 03:04
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));
}
}
- 2.新的for循环
- 2.新的for循环
- JDK5.0新特性系列---2.新的for循环
- For循环的新特性
- for循环的新特性
- JAVA的for循环新用法:foreach
- C++11的for循环新特性
- 对于 For 循环的新认识
- C++11 for循环的新用法
- 判断当前for循环为一层新的循环方法
- java1.5新特性for循环的新写法
- JAVA1.5 增强的for 循环的新特性
- c++11的新特性---基于范围的for循环
- Java1.5中新加入的一种for循环——增强型for循环
- J2SE 1.5 新功能特性:新的For循环
- J2SE 1.5 新功能特性:新的For循环
- java 1.5中for循环的新写法
- java 1.5中for循环的新写法
- 1.自动装箱和拆箱
- 关于Sqlserver2012分页的新功能尝试
- dbus实例讲解(二下):消息和消息总线
- 线程条件变量pthread_cond_t
- javaScript namespace
- 2.新的for循环
- android开发中listview 单选多选
- 在SDK中打开其他接入应用的解决方案
- ios开发笔记 (1)--数组
- dbus实例讲解(三):数据类型和dteeth
- 二叉树 递归 非递归 遍历 C语言 可直接运行
- 3.枚举类型
- dbus实例讲解(四上):使用dbus-glib
- URL重写