2.7、程序实例
现要求设计一个表示学生的类,里面有学生的三项成绩,计算机成绩、数学成绩、英语成绩
要求可以求总分、平均分、最高、最低分,并且可以输出一个学生的完整信息。问:此类该如何设计?
程序开发步骤:
- 根据要求定义所需要的类
- 根据要求规划出类的属性:name、age、computer、english、math
- 所有的属性必须封装:private
- 所有的属性必须通过getter和setter访问
- 如有需要增加构造方法,为属性赋值
- 所有的信息不要在类中直接输出,而是交给调用处输出(在类中不能出现System.out.println()语句)
class Student{
private String name;
private int age;
private float english;
private float computer;
private float math;
public Student(){}
public Student(String name,int age,float english,float computer,float math){
this.setName(name);
this.setAge(age);
this.setEnglish(english);
this.setComputer(computer);
this.setMath(math);
}
public float sum(){
return english + computer + math;
}
public float avg(){
return this.sum()/3;
}
public float max(){
float max = computer > math?computer:math;
max = max>english?max:english;
return max;
}
public float min(){
float min = computer<math?computer:math;
min = min<english?min:english;
return min;
}
public String getInfo(){
return "学生信息:\n"+
"姓名:" + this.name + "\n" +
"年龄:" + this.age + "\n" +
"数学成绩:" + this.math + "\n" +
"英语成绩:" + this.english + "\n" +
"计算机成绩:" + this.computer;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){
this.age = age;
}
public void setEnglish(float english){
this.english = english;
}
public void setComputer(float computer){
this.computer = computer;
}
public void setMath(float math){
this.math = math;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public float getEnglish(){
return english;
}
public float getComputer(){
return computer;
}
public float getMath(){
return math;
}
}
public class Demo {
public static void main(String args[]){
Student stu = new Student("张三",30,89.0f,91.0f,87.0f);
System.out.println("总分:" + stu.sum());
System.out.println("平均分:" + stu.avg());
System.out.println("最过分:" + stu.max());
System.out.println("最低分" + stu.min());
System.out.println(stu.getInfo());
}
}
转载请注明来源