本章目标
掌握类的基本分析思路
应用思路分析具体的题目
程序分析思路
在具体题目讲解之前先给出读者一些分析的思路:
1、 根据要求写出类所包含的属性;
2、 所有的属性都必须进行封装(private);
3、 封装之后的属性通过setter和getter设置和取得;
4、 如果需要可以加入若干构造方法;
5、 再根据其他要求添加相应的方法;
6、类中的所有方法都不要直接输出,而是交给被调用处输出。
题目要求
定义并测试一个名为Student的类,包括属性有“学号”、“姓名”,以及3门课程“数学”、“英语”和“计算机”的成绩,包括的方法有计算3门课程的“总分”、“平均分”、“最高分”及“最低分”。
属性及类型
定义出方法(普通方法、构造方法)
设计类图
public class Student {//定义学生类
private String stuno;//学生编号
private String name;//学生姓名
private float math;//数学成绩
private float english;//英语成绩
private float computer;//计算机成绩
public Student() {//定义无参构造
}
//定义有 5 个参数的构造方法,为类中的属性初始化
public Student(String stuno, String name, float math, float english,
float computer) {
this.setStuno(stuno);//设置编号
this.setName(name);//设置姓名
this.setMath(math);//设置数学成绩
this.setEnglish(english);//设置英语成绩
this.setComputer(computer);//设置计算机成绩
}
public String getStuno() {//取得编号
return stuno;
}
public void setStuno(String stuno) {//设置编号
this.stuno = stuno;
}
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;
}
public float sum(){//计算总分
return this.math+this.english+this.computer;
}
public float avg(){//计算平均分
return this.sum()/3;//总分除以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 class ExampleDemo01 {
public static void main(String[] args) {
Student stu = null;
stu = new Student("cy-0016","chaoyi",95.0f,89.0f,96.0f);//声明对象
//实例化 Student 对象,并通过构造方法赋值
System.out.println("学生编号:"+stu.getStuno());
System.out.println("学生姓名:"+stu.getName());
System.out.println("数学成绩:"+stu.getMath());
System.out.println("英语成绩:"+stu.getEnglish());
System.out.println("计算机成绩:"+stu.getComputer());
System.out.println("最高分:"+stu.max());
System.out.println("最低分:"+stu.min());
}
/*
* 学生编号:cy-0016
* 学生姓名:chaoyi
* 数学成绩:95.0
* 英语成绩:89.0
* 计算机成绩:96.0
* 最高分:96.0
* 最低分:89.0
* */
}