“对一共有10名学生的班级进行一次测试。已知每个学生这次测试的成绩,求这次测验的班级平均成绩、最高成绩、最低成绩,并统计本次考试成绩的分布情况。”
用面向对象的思路写成类的形式,设计学生类和班级类,使用对象的组合,班级类中的成员为学生类的对象学生。
源代码如下:
class Student { //学生类 String name; double score; Student(String name, double score) { this.name = name; this.score = score; } }
class Class { //班级类 Student[] s; Class(Student[] s) { this.s = s; } double getAverage() { //平均成绩 double sum = 0; for (int i = 0; i < s.length; i++) { sum += s[i].score; } return sum / s.length; } double getMax() { //最高成绩 double maxScore = 0; for (int i = 0; i < s.length; i++) { if (s[i].score > maxScore) { maxScore = s[i].score; } } return maxScore; } double getMin() { //最低成绩 double minScore = 100; for (int i = 0; i < s.length; i++) { if (s[i].score < minScore) { minScore = s[i].score; } } return minScore; } String gradeDistribution() { //本次考试成绩的分布情况 int great = 0; int good = 0; int pass = 0; int failure = 0; for (int i = 0; i < s.length; i++) { int grade = (int) (s[i].score / 10); switch (grade) { case 10: case 9: great++; break; case 8: case 7: good++; break; case 6: pass++; break; default: failure++; break; } } return "优秀:" + great + " 良好:" + good + " 及格:" + pass + " 不及格:" + failure; } }
public class Test2 { public static void main(String[] args) { String[] name = {"weimeng", "zhao", "qian", "sun", "li", "zhou", "wu", "zheng", "wang", "zhang"}; double[] score = {100, 70, 81, 90, 60, 50, 78, 45, 58, 80}; Student[] stu = new Student[10]; for (int i = 0; i < stu.length; i++) { stu[i] = new Student(name[i], score[i]); } Class c = new Class(stu); System.out.println("平均分:" + c.getAverage()); System.out.println("最高分:" + c.getMax()); System.out.println("最低分:" + c.getMin()); System.out.println("成绩分布:" + c.gradeDistribution()); } }
运行结果:
平均分:71.2 最高分:100.0 最低分:45.0 成绩分布:优秀:2 良好:4 及格:1 不及格:3