一个学生对象。

以下是实现代码:

public class Student {
    private String name;
    private int id;
    private double score1;
    private double score2;
    private double score3;
    private double averageScore;
    private int credit1;
    private int credit2;
    private int credit3;
    private double totalGPA;

    public Student(String name, int id, double score1, double score2, double score3, int credit1, int credit2, int credit3) {
        this.name = name;
        this.id = id;
        this.score1 = score1;
        this.score2 = score2;
        this.score3 = score3;
        this.credit1 = credit1;
        this.credit2 = credit2;
        this.credit3 = credit3;

        // 计算平均分和总GPA
        this.averageScore = (score1 + score2 + score3) / 3;
        double totalCredit = credit1 + credit2 + credit3;
        this.totalGPA = (scoreToGPA(score1) * credit1 + scoreToGPA(score2) * credit2 + scoreToGPA(score3) * credit3) / totalCredit;
    }

    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }

    public double getScore1() {
        return score1;
    }

    public double getScore2() {
        return score2;
    }

    public double getScore3() {
        return score3;
    }

    public double getAverageScore() {
        return averageScore;
    }

    public int getCredit1() {
        return credit1;
    }

    public int getCredit2() {
        return credit2;
    }

    public int getCredit3() {
        return credit3;
    }

    public double getTotalGPA() {
        return totalGPA;
    }

    // 将分数转换为GPA
    private double scoreToGPA(double score) {
        if (score >= 90) {
            return 4.0;
        } else if (score >= 85) {
            return 3.7;
        } else if (score >= 82) {
            return 3.3;
        } else if (score >= 78) {
            return 3.0;
        } else if (score >= 75) {
            return 2.7;
        } else if (score >= 72) {
            return 2.3;
        } else if (score >= 68) {
            return 2.0;
        } else if (score >= 64) {
            return 1.5;
        } else if (score >= 60) {
            return 1.0;
        } else {
            return 0.0;
        }
    }

    public static void main(String[] args) {
        Student student = new Student("张三", 20190001, 80, 85, 90, 3, 4, 2);
        System.out.println("姓名:" + student.getName());
        System.out.println("学号:" + student.getId());
        System.out.println("平均分:" + student.getAverageScore());
        System.out.println("总GPA:" + student.getTotalGPA());
    }
}

在构造方法中,我们传入了学生的姓名、学号、三门课程的成绩和学分。然后我们通过计算平均分和总GPA,并保存到相应的实例变量中。在实现中,我们使用了一个私有的方法scoreToGPA来将分数转换为GPA。最后,我们提供了一个main方法来测试我们的程序。我们创建了一个学生对象,并打印出他的姓名、学号、平均分和总GPA

Java通过构造方法实现全校学生3门课程的平均分和学分计算他的总gpa并且实例化

原文地址: https://www.cveoy.top/t/topic/epC2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录