定义一个学生类Student,成员变量包括姓名、性别、年龄、语文成绩、数学成绩和英语成绩,求总分和平均分。
4条回答 默认 最新
- 一枚小爪哇 2021-11-01 12:59关注
控制台输入成绩,根据菜单栏选择显示:
public class Student { private String name; private String sex; private int age; private double chineseScore; private double mathScore; private double englishScore; public Student() { } public Student(String name, String sex, int age, double chineseScore, double mathScore, double englishScore) { this.name = name; this.sex = sex; this.age = age; this.chineseScore = chineseScore; this.mathScore = mathScore; this.englishScore = englishScore; } public double getTotalScore() { return englishScore + mathScore + chineseScore; } public double getAvgScore() { return getTotalScore() / 3.0; } @Override public String toString() { return "学生信息: {" + "姓名: '" + name + '\'' + ", 性别: '" + sex + '\'' + ", 年龄: " + age + ", 语文: " + chineseScore + ", 数学: " + mathScore + ", 英语: " + englishScore + '}'; } }
public class Grade { private Student student; public Grade(Student student) { this.student = student; } public void menu() { System.out.println("菜单栏:"); System.out.println("1. 显示学生信息,"); System.out.println("2. 求成绩总分,"); System.out.println("3. 求成绩平均分"); System.out.println("0. 退出"); } public void show(int type) { switch (type) { case 1: System.out.println(this.student.toString()); break; case 2: System.out.println(this.student.getTotalScore()); break; case 3: System.out.println(this.student.getAvgScore()); break; default: System.out.println("输入错误!"); } } }
public class TestMain { public static void main(String[] args) { System.out.println("输入学生信息:"); Scanner scanner = new Scanner(System.in); System.out.println("输入学生姓名:"); String name = scanner.next(); System.out.println("输入学生性别:"); String sex = scanner.next(); System.out.println("输入学生年龄:"); int age = scanner.nextInt(); System.out.println("输入学生语文成绩:"); double chineseScore = scanner.nextDouble(); System.out.println("输入学生数学成绩:"); double mathScore = scanner.nextDouble(); System.out.println("输入学生英语:"); double englishScore = scanner.nextDouble(); Student student = new Student(name, sex, age, chineseScore, mathScore, englishScore); Grade grade = new Grade(student); grade.menu(); while (true){ int type = scanner.nextInt(); if (type == 0) { break; } grade.show(type); } } }
运行结果:
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 5无用 3