我一直在搜索所有地方,但是找不到答案。
我正在尝试创建一个ArrayList来在用户定义的类中存储10个等级,因此我可以在Client类中调用它,并使用Scanner(System.in)输入等级,然后将它们一起输出,但是我不知道是否有可能这样做,而且我到处都在寻找答案。请帮忙。
到目前为止,这是我定义的用户定义类
import java.util.ArrayList;
public class Student {
private String student;
private String courseName;
private double grade;
private double avg;
private double total;
private double max;
private double min;
//Constructor w/o arguments
public Student() {
this.student = "";
this.courseName = "";
this.grade = 0.0;
}
//Constructor with arguments
public Student(String student, String courseName, double grade, double avg, double total, double max, double min) {
this.student = student;
this.courseName = courseName;
this.grade = grade;
}
//Getters
public String getStudent(){
return this.student;
}
public String getCourseName() {
return this.courseName;
}
//Setters
public void setStudent(String student) {
this.student = student;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
//Returns average off the 10 grades
public double calculateAvg() {
total += grade; //add all grades for average
avg = total / 10;
return avg;
}
//Highest Grade
public double highGrade() {
return max = Math.max(grade, max);
}
//Lowest Grade
public double lowGrade() {
return min = Math.min(grade, min);
}
ArrayList<Student>listGrades = new ArrayList<Student>();
答案 0 :(得分:1)
不确定要了解什么,但是可以做到:
class Student {
private final List<Double> grades = new ArrayList<>(10);
private final String name;
// Constructor, getters & setters omitted.
}
// ..
Student student = // ...
for (int i=0; i<10; i++) {
System.out.println("Please enter the "+(i+1)+"th grade:");
student.getGrades().add(scanner.nextDouble());
}
// ..
Student student = // ...
student.getGrades().forEach(System.out::println);
注意,这不是最佳方法。您可以在https://codereview.stackexchange.com/社区中搜索“学生成绩java” ,以查找有关类似问题的大量评论。
答案 1 :(得分:0)
在构造函数或其他方法中将其初始化: [https://www.geeksforgeeks.org/initialize-an-arraylist-in-java/][1]
答案 2 :(得分:0)
您应该尝试这样的事情。
public static void main(String[] args) {
System.out.println("Enter number of Students :");
Scanner scanner = new Scanner(System.in);
Student s=new Student("gagan","Math",0.0d,0.0d, 0.0d, 0.0d,0.0d);
s.listGrades.add(s);
for(Student s1:s.listGrades) {
System.out.println("Enter Grade for student"+s.getStudent()+": ");
s1.setGrade(scanner.nextDouble());
}
scanner.close();
}