欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

学生成绩(类的应用)

程序员文章站 2024-01-15 19:42:10
...

成绩类:

public class Grade {
	int Eng,Mat,Chi;
	
	public Grade(int Eng,int Mat,int Chi){
		this.Eng=Eng;
		this.Mat=Mat;
		this.Chi=Chi;
	}
	
	int getEng(){
		return this.Eng;
	}
	
	int getMat(){
		return Mat;
	}
	
	int getChi(){
		return Chi;
	}
	
	int getGrade(){
		int Sum;
		Sum=Eng+Mat+Chi;
		return Sum;
	}
}


学生类:

public class Student {
    public String studentID;
    public String studentName;
    public Grade grade;
    
    public Student(String ID,String name,Grade grade){
    	studentID = ID;
    	studentName = name;
    	this.grade = grade;
    }
    
    public String getID(){
    	return studentID;
    }
    
    public String getName(){
    	return studentName;
    }
    
    public Grade getGrade(){
    	return grade;
    }
}

主类:

import java.util.*;
public class MainStudent {
	public static void main(String[] args) {
		
		Scanner in = new Scanner(System.in);
		int StudentNum;
		System.out.println("请输入学生人数");
		StudentNum=in.nextInt();
		System.out.println("===========================================================");
		
		List<Student> list = new ArrayList<Student>();
		
		for (int i = 0;i<StudentNum;i++){
            System.out.println("输入学生的学号:");
            String ID = in.next();

            System.out.println("输入学生的姓名:");
            String name = in.next();
            System.out.println("输入英语科目的成绩:");
            int Eng = in.nextInt();
            
            System.out.println("输入数学科目的成绩:");
            int Mat = in.nextInt();

            System.out.println("输入语文科目的成绩:");
            int Chi = in.nextInt();
            
            Grade grade = new Grade(Eng,Mat,Chi);
            Student student = new Student(ID,name,grade);
            list.add(student);
            
            System.out.println("===========================================================");
		}
		
		list.sort(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                if(o1.getGrade().getGrade()>o2.getGrade().getGrade())
                    return -1;
                else
                    return 1;
            }

        });
		
		for (Student student:list){
			System.out.println("学号:"+student.getID()+"\t"+"姓名:"+student.getName()+"\t"
                    + "总分:"+student.getGrade().getGrade());
		}
	}
}