赞
赏
定义一个 Collection 类型的 集合 存储分数,使用增强 for 循环遍历元素。
请定义一个 Collection 类型的集合,存储以下分数信息:
88.5,39.2,77.1,56.8,89.0,99.0,59.5
请编程实现以下功能:
public class Test {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
// 创建集合
Collection<Double> coll = new ArrayList<Double>();
// 创建分数数组
double[] arr = {88.5,39.2,77.1,56.8,89.0,99.0,59.5};
// 将分数存入集合
for (int i = 0; i < arr.length; i++) {
coll.add(arr[i]);
}
// 遍历所有元素
System.out.print("打印所有分数:");
for(double score : coll){
System.out.print(score + " ");
}
// 打印不及格分数
System.out.print("\n打印不及格分数:");
for(double score : coll){
if(score < 60){
System.out.print(score + " ");
}
}
// 打印不及格分数的数量和平均分
double sum = 0;
int count = 0;
double avg = 0;
for(double score : coll){
if(score < 60){
// 计算不及格分数总和
sum += score;
// 计算不及格个数
count++;
}
}
System.out.print("\n不及格分数个数为:");
System.out.print(count);
System.out.print("\n平均分为:");
// 计算平均值
avg = sum / count;
System.out.print(avg);
// 得出最高分
double max = 0;
for(double score : coll){
if(score > max){
max = score;
}
}
System.out.print("\n最高分为:");
System.out.print(max);
}
}
运行结果如下图:
以上案例使用增强 for 循环遍历 Collection 集合,并按要求打印分数。