A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© _J2EE_LiXiZhen 中级黑马   /  2017-11-13 23:47  /  1111 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

自定义学生类:包含姓名,年龄,成绩属性.私有成员变量,生成无参,有参构造方法,生成get/set方法.
创建5个学生放到ArrayList中.使用迭代器获取每个学生信息.统计总分,平均分,最高分,最低分并输出
[Java] 纯文本查看 复制代码
//自定义学生类:包含姓名,年龄,成绩属性.私有成员变量,生成无参,有参构造方法,生成get/set方法.

public class Student {
	//姓名
	private String name;
	//年龄
	private int age;
	//成绩
	private int score;
	
	public Student() {
		// TODO Auto-generated constructor stub
	}

	public Student(String name, int age, int score) {
		super();
		this.name = name;
		this.age = age;
		this.score = score;
	}

	//get/set
	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 class Test {
	private static final String ArrayList = null;

	public static void main(String[] args) {
		// 创建scanner对象
		Scanner sc = new Scanner(System.in);
		// 创建ArrayList集合
		Collection<Student> coll = new ArrayList<Student>();
		// 控制台循环输入
		for (int i = 0; i < 5; i++) {
			System.out.println("请输入第" + (i + 1) + "个学生姓名:");
			String name = sc.next();
			System.out.println("请输入第" + (i + 1) + "个学生年龄:");
			int age = sc.nextInt();
			System.out.println("请输入第" + (i + 1) + "个学生成绩:");
			int score = sc.nextInt();
			// 学生对象添加到集合
			coll.add(new Student(name, age, score));
		}
		// 创建迭代器
		Iterator<Student> it = coll.iterator();
		// 遍历集合
		while (it.hasNext()) {
			Student stu = it.next();
			// 打印学生信息
			System.out.println("姓名: " + stu.getName() + " 年龄: " + stu.getAge() + " 成绩: " + stu.getScore());
		}

		// coll向下转型
		ArrayList<Student> arr = (ArrayList<Student>) coll;

		// 成绩最高分
		int maxScore = arr.get(0).getScore();
		// 成绩最低分
		int minScore = arr.get(0).getScore();
		// 成绩和
		int sumScore = 0;

		// 循环遍历集合
		for (int i = 1; i < coll.size(); i++) {
			if (maxScore < arr.get(i).getScore())
				maxScore = arr.get(i).getScore();
			if (minScore > arr.get(i).getScore())
				minScore = arr.get(i).getScore();
			sumScore += arr.get(i).getScore();
		}

		// 成绩平均分
		int avgScore = sumScore / (arr.size());
		System.out.println("成绩最高分为: " + maxScore);
		System.out.println("成绩最低分为: " + minScore);
		System.out.println("成绩平均分为: " + avgScore);
	}
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马