public class Student {
// 学号
private int ID;
// 姓名
private String name;
// 两门课成绩
private double javamark;
// 网页成绩
private double webmark;
// 总成绩
private Double sum;
// 平均成绩
private Double avg;
public Student() {
}
public Student(int ID, String name, double javamark, double webmark) {
this.ID = ID;
this.name = name;
this.javamark = javamark;
this.webmark = webmark;
}
public double sum() {
if (sum == null) {
sum = javamark + webmark;
}
return sum;
}
public double avg() {
if (avg == null) {
avg = sum() / 2;
}
return avg;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getJavamark() {
return javamark;
}
public void setJavamark(double javamark) {
this.javamark = javamark;
}
public double getWebmark() {
return webmark;
}
public void setWebmark(double webmark) {
this.webmark = webmark;
}
public Double getSum() {
return sum;
}
public void setSum(double sum) {
this.sum = sum;
}
public Double getAvg() {
return avg;
}
public void setAvg(double avg) {
this.avg = avg;
}
}
测试类:
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
public class TestKeShe1 {
public static void main(String[] args) {
Listlist = new ArrayList<>();
list.add(new Student(1, "张三", 98, 95));
list.add(new Student(2, "李四", 80, 90));
list.add(new Student(3, "王五", 90, 89));
double sumJava = 0;
double sumWeb = 0;
double maxJava = list.get(0).getJavamark();
double minJava = list.get(0).getJavamark();
for (Student stu : list) {
sumJava += stu.getJavamark();
sumWeb += stu.getWebmark();
if (stu.getJavamark() > maxJava) {
maxJava = stu.getJavamark();
}
if (stu.getJavamark() < minJava) {
minJava = stu.getJavamark();
}
}
System.out.println("Java总分为:" + sumJava + ", 网页总分为:" + sumWeb);
// 平均分结果保留一位小数
double avgJava = new BigDecimal(sumJava).divide(new BigDecimal(3), 1, RoundingMode.HALF_UP).doubleValue();
double avgWeb = new BigDecimal(sumWeb).divide(new BigDecimal(3), 1, RoundingMode.HALF_UP).doubleValue();
System.out.println("Java平均分为:" + avgJava + ", 网页平均分为:" + avgWeb);
System.out.println("Java最高分为:" + maxJava + ", Java最低分为:" + minJava);
}
}