1.1 实例讲解——类设计分析
题目:
定义并测试一个名为Student的类,包括的属性有“学号”、“姓名”以及3门课程“数学”、“英语”和“计算机”的成绩,包括的方法有计算3门课程的“总分”、“平均分”、“最高分”及“最低分”。
1、本类中的属性及类型,如下图:
2、定义出需要的方法:
类图如下:
实现代码:
class Student {
private String nonum;
private String name;
private float math;
private float english;
private float computer;
public Student() {
}
public Student(String nonum, String name, float math, float english,
float computer) {
this.setNonum(nonum);
this.setName(name);
this.setMath(math);
this.setEnglish(english);
this.setComputer(computer);
}
public float sum() {
return math + english + computer;
}
public float avg() {
return sum() / 3;
}
public float max() {
float max = math;
max = max > computer ? max : computer;
max = max > english ? max : english;
return max;
}
public float min() {
float min = math;
min = min < computer ? min : computer;
min = min < english ? min : english;
return min;
}
public String getNonum() {
return nonum;
}
public void setNonum(String nonum) {
this.nonum = nonum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getMath() {
return math;
}
public void setMath(float math) {
this.math = math;
}
public float getEnglish() {
return english;
}
public void setEnglish(float english) {
this.english = english;
}
public float getComputer() {
return computer;
}
public void setComputer(float computer) {
this.computer = computer;
}
}
class ExampleDemo01 {
public static void main(String[] args) {
Student st = new Student("MLDN-33","李刚",90.0f,99.0f,89.0f);
System.out.println("学生编号:" + st.getNonum());
System.out.println("学生姓名:" + st.getName());
System.out.println("数学成绩:" + st.getMath());
System.out.println("英语成绩:" + st.getEnglish());
System.out.println("计算机成绩:" + st.getComputer());
System.out.println("总成绩:" + st.sum());
System.out.println("最高分:" + st.max());
System.out.println("最低分:" + st.min());
}
}
运行结果:
学生编号:MLDN-33
学生姓名:李刚
数学成绩:90.0
英语成绩:99.0
计算机成绩:89.0
总成绩:278.0
最高分:99.0
最低分:89.0
转载于:https://blog.51cto.com/5838311/990481