java题:设计一个班有10名学生,每个学生有姓名、学号、成绩等信息,利用对象数组的概念编程,求平均成绩
1个回答
展开全部
package org.dylan.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Class {
private List<Student> students = new ArrayList<Student>();
//求班级所有学生的平均成绩
public double avg() {
double sum = 0;
for (Student stu : students) {
System.out.println("学生["+stu.name+"]的成绩为:" + stu.score);
sum += stu.score;
}
return sum / students.size();
}
//给班级中增加一个学生
public void addStudent(Student stu) {
students.add(stu);
}
public static void main(String[] args) {
Class cla = new Class();//创建一个班级,
//为班级增加10个学生
for(int i = 0; i < 10; i++){
String name = "student" + i;
String code = "code" + i;
cla.addStudent(new Student(name,code,geneScore()));
}
System.out.println("班级成员的平均成绩为:" + cla.avg());
}
//随机生成成绩
public static double geneScore(){
return new Random().nextInt(60) + 40;
}
}
class Student {
String name;
String code;
double score;
public Student(String name, String code, double score) {
this.name = name;
this.code = code;
this.score = score;
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Class {
private List<Student> students = new ArrayList<Student>();
//求班级所有学生的平均成绩
public double avg() {
double sum = 0;
for (Student stu : students) {
System.out.println("学生["+stu.name+"]的成绩为:" + stu.score);
sum += stu.score;
}
return sum / students.size();
}
//给班级中增加一个学生
public void addStudent(Student stu) {
students.add(stu);
}
public static void main(String[] args) {
Class cla = new Class();//创建一个班级,
//为班级增加10个学生
for(int i = 0; i < 10; i++){
String name = "student" + i;
String code = "code" + i;
cla.addStudent(new Student(name,code,geneScore()));
}
System.out.println("班级成员的平均成绩为:" + cla.avg());
}
//随机生成成绩
public static double geneScore(){
return new Random().nextInt(60) + 40;
}
}
class Student {
String name;
String code;
double score;
public Student(String name, String code, double score) {
this.name = name;
this.code = code;
this.score = score;
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询