使用面向对象方法编程习题:有三个学生,每个学生有姓名、两门成绩; 计算每个学生的平均分、总分、并按总分降序输出
问题分析:学生类:
属性:
private String name;
private double score1;
private double score2;
方法:构造函数中赋值:
public Student(String name, double score1, double score2) {
this.name = name;
this.score1 = score1;
this.score2 = score2;
}
总分计算:
public double scoreSum(){
return score1 + score2;
}
平均分计算:
public double scoreAvg(){
// 调用求总分函数
double sum = scoreSum();
return sum/2;
}
输出:
public static void outPut(Student[] students){
for(int i=0; i < students.length; i++){
System.out.println(students[i].name+"\t"+students[i].scoreSum());
}
}
排序:
// 排序(降序): 通过改变学生对象数组中的学生位置来达到排序的目的
public static void studentSort(Student[] students){
// bubble sort
for(int i =0 ; i < students.length; i++) {
for(int j=0; j<students.length-i-1; j++){
if(students[j].scoreSum() > students[j+1].scoreSum()){
Student temp = students[j];
students[j] = students[j+1];
students[j+1] = temp;
}
}
}
重点:对象数组的使用
一般我们使用数组时:
int[] a = new int[3];
String[] b = new String[3]
对象数组:
Student[] Students =new Student[]{student1,student2,student3};
为何会使用对象数组:
在我们排序时,因为我们要使用for循环,并且输出排序后的学生的姓名
和成绩总分,我们输出的是一个对象的属性,因此,在排序过程中,我们只需要调这个对象的总分方法来比较,然后在对象数组中调换他们的顺序,我们就可以实现排序了。
具体代码如下:
package com.demo;
public class Student {
private String name;
private double score1;
private double score2;
public Student(String name, double score1, double score2) {
this.name = name;
this.score1 = score1;
this.score2 = score2;
}
// 总分
public double scoreSum(){
return score1 + score2;
}
// 平均
public double scoreAvg(){
// 调用求总分函数
double sum = scoreSum();
return sum/2;
}
// 输出
public static void outPut(Student[] students){
for(int i=0; i < students.length; i++){
System.out.println(students[i].name+"\t"+students[i].scoreSum());
}
}
// 排序(降序): 通过改变学生对象数组中的学生位置来达到排序的目的
public static void studentSort(Student[] students){
// bubble sort
for(int i =0 ; i < students.length; i++) {
for(int j=0; j<students.length-i-1; j++){
if(students[j].scoreSum() > students[j+1].scoreSum()){
Student temp = students[j];
students[j] = students[j+1];
students[j+1] = temp;
}
}
}
}
public static void main(String[] args) {
Student student1 = new Student("zs",99,88);
Student student2 = new Student("ls",89,88);
Student student3 = new Student("ww",88,100);
// studentOutput(student1,student2);
// 对象数组,排序按学生排序,所以我们可以使用对象数组中的每个学生的成绩sum函数的元素来比较。
Student[] Students =new Student[]{student1,student2,student3};
System.out.println("排序前");
outPut(Students);
System.out.println("排序后");
studentSort(Students);
outPut(Students);
}
}