设计一个学生的类,里面包含类学的 “姓名”、“学号”、“数学成绩”、“英语成绩” 和 “计算机成绩”。类里面的方法有计算三门成绩的平均分,总分,最低分和最高分。
从题目中我们了解到要定义一个学生类,里面的属性有 “学号”、“姓名”、“数学成绩”、“英语成绩” 和 “计算机成绩”。然后有四个方法,计算总分,平均分,最高分和最低分。
学号和姓名我们可以使用 String 类型,分数我们可以使用 float 类型。
我们定义一个 Student 类
package com.haicoder.net.clas;
public class Student {
//属性定义为 private 类型
private String stuName; //学生姓名
private String stuNo; //学号
private float math; //数学成绩
private float english; //英语成绩
private float computer; //计算机成绩
//定义构造函数
public Student(String stuName, String stuNo, float math, float english, float computer) {
this.stuName = stuName;
this.stuNo = stuNo;
this.math = math;
this.english = english;
this.computer = computer;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
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 math + english + computer;
}
public float avg() {
return this.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 < english ? min : english;
min = min < computer ? min : computer;
return min;
}
}
测试类为:
package com.haicoder.net.clas;
public class StudentTest {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)");
Student student = new Student("嗨客网", "001", 95.0f, 85.5f, 99.5f);
System.out.println("学生名称: " + student.getStuName());
System.out.println("学生学号: " + student.getStuNo());
System.out.println("数学成绩为: " + student.getMath());
System.out.println("英语成绩为: " + student.getEnglish());
System.out.println("计算机成绩为: " + student.getComputer());
System.out.println("最高成绩为: " + student.max());
System.out.println("最低成绩为 : " + student.min());
System.out.println("成绩总合: " + student.sum());
System.out.println("平均成绩为: " + student.avg());
}
}
运行结果如下:
我们使用了 三目运算符,运用了基本的算数语法,也用了构造函数对学生类里面的属性赋值。