java小实验-初步使用类

java小实验-初步使用类

定义一个学生类,包含的成员有:姓名,学号,绩优成绩,总人数,平均绩优成绩等数据成员,和数据的getter 和setter方法,以及toString 方法,合理使用 public, private, static,final等限定词。主函数中创建5个学生对象,输出每个学生的个性信息,以及全部学生对象的全局信息。

Student.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public class Student {  
private String name;
private String id;
private double score;
private static int total;
private static double average;

Student(String name, String id, double score) {
this.name = name;
this.id = id;
this.score = score;
average = (average * total++ + score) / total;
}

public String GetName(){
return this.name;
}

public String GetId(){
return this.id;
}

public double GetScore(){
return this.score;
}

public void SetName(String name){
this.name = name;
}

public void SetId(String id){
this.id = id;
}

public void SetScore(double score){
var lastScore = this.score;
average = (average * total - lastScore + score) / total;
this.score = score;
}

public int GetCount(){
return total;
}

public double GetAverage(){
return average;
}

@Override
public String toString(){
return String.format("学号%s 姓名%s 成绩%f", GetId(), GetName(), GetScore());
}
}

Main.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Main {  
public static void main(String[] args) {
var student1 = new Student("test1", "114514", 60.1);
System.out.println(student1.toString());

var student2 = new Student("test2", "114514", 60.1);
student2.SetId("1919810");
System.out.println(student2.toString());

var student3 = new Student("test3", "114514", 60.1);
System.out.println(student3.toString());

var student4 = new Student("test4", "114514", 60.1);
System.out.println(student4.toString());

var student5 = new Student("test5", "114514", 60.1);
System.out.println(student5.toString());

System.out.println("平均成绩 " + student1.GetAverage());
student3.SetScore(80.5);
System.out.println("平均成绩 " + student1.GetAverage());
}
}

java小实验-初步使用类
http://cvrain.cloudvl.cn/2023/11/18/Java/java-example-2/
作者
ClaudeRainer
发布于
2023年11月18日
许可协议