1请用javaBean规范设计一个学生类Student具有: 属性:no学号、name姓名 和score成绩 功能:输出一位学生的数据内容toString、计算学生的平均分getAvg2在main方法中创建五个学生信息并定义一个对象数组用于存储创建的五位学生的数据 使用Student类的getAvg方法计算出这些学生的平均分;并打印所有学生的信息。思路: 在Student类中定义getAvg方
- Student.java
public class Student { private int no; private String name; private double score;
public Student(int no, String name, double score) {
this.no = no;
this.name = name;
this.score = score;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
@Override
public String toString() {
return "Student{" +
"no=" + no +
", name='" + name + '\'' +
", score=" + score +
'}';
}
public static double getAvg(Student[] students) {
double sum = 0;
for (Student student : students) {
sum += student.getScore();
}
return sum / students.length;
}
}
- Main.java
public class Main { public static void main(String[] args) { Student[] students = new Student[5]; students[0] = new Student(1, "Tom", 90); students[1] = new Student(2, "Jerry", 85); students[2] = new Student(3, "Alice", 95); students[3] = new Student(4, "Bob", 88); students[4] = new Student(5, "Lisa", 92);
double avg = Student.getAvg(students);
System.out.println("Average score: " + avg);
for (Student student : students) {
System.out.println(student.toString());
}
}
}
输出结果:
Average score: 90.0 Student{no=1, name='Tom', score=90.0} Student{no=2, name='Jerry', score=85.0} Student{no=3, name='Alice', score=95.0} Student{no=4, name='Bob', score=88.0} Student{no=5, name='Lisa', score=92.0
原文地址: http://www.cveoy.top/t/topic/h8P7 著作权归作者所有。请勿转载和采集!