首页 > 代码库 > 集合练习4
集合练习4
第三题 有如下Student 对象,
private String name;
private int age;
private int score;
private String classNum;
其中,classNum 表示学生的班号,例如“class05”。 有如下List
List list = new ArrayList();
list.add(new Student(“Tom”, 18, 100, “class05”));
list.add(new Student(“Jerry”, 22, 70, “class04”));
list.add(new Student(“Owen”, 25, 90, “class05”));
list.add(new Student(“Jim”, 30,80 , “class05”));
list.add(new Student(“Steve”, 28, 66, “class06”));
list.add(new Student(“Kevin”, 24, 100, “class04”));
在这个list 的基础上,完成下列要求:
1) 计算所有学生的平均年龄
2) 计算各个班级的平均分
package com.jihelianxi;public class Lianxi3 { private String name; private int age; private int score; private String classNum; public Lianxi3(String name, int age, int score, String classNum) { super(); this.name = name; this.age = age; this.score = score; this.classNum = classNum; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public String getClassNum() { return classNum; } public void setClassNum(String classNum) { this.classNum = classNum; } }
main方法:
package com.jihelianxi;import java.util.ArrayList;import java.util.List;public class Lianxi31 { public static void main(String[] args) { List<Lianxi3> list=new ArrayList<>(); list.add(new Lianxi3("Tom", 18, 100, "class05")); list.add(new Lianxi3("Jerry", 22, 70, "class04")); list.add(new Lianxi3("Owen", 25, 90, "class05")); list.add(new Lianxi3("Jim", 30,80 , "class05")); list.add(new Lianxi3("Steve", 28, 66, "class06")); list.add(new Lianxi3("Kevin", 24, 100, "class04")); double pingju=0; for(int i=0;i<list.size();i++) { Integer in=list.get(i).getAge(); pingju=(pingju+in); } double s=pingju/list.size(); System.out.println("平均年龄:"+s); int num1=0; int num2=0; int num3=0; int score1=0; int score2=0; int score3=0; for(int i =0;i<list.size();i++) { Lianxi3 st =list.get(i); if(st.getClassNum()=="class04") { num1++; score1+=st.getScore(); } else if(st.getClassNum()=="class05") { num2++; score2+=st.getScore(); } else { num3++; score3+=st.getScore(); } } System.out.println("class04的平均分:"+(score1/num1)); System.out.println("class05的平均分:"+(score2/num2)); System.out.println("class06的平均分:"+(score3/num3)); }}
结果:
集合练习4
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。