gpt4 book ai didi

java - 在用户定义的 Java 类中创建 ArrayList

转载 作者:行者123 更新时间:2023-12-02 10:30:37 25 4
gpt4 key购买 nike

我到处寻找但找不到答案。

我正在尝试制作一个 ArrayList 在用户定义的类中存储 10 个成绩,这样我就可以在客户端类中调用它并使用 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>();

最佳答案

不确定你想要什么,但那就可以了:

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”社区可以找到很多类似问题的评论。

关于java - 在用户定义的 Java 类中创建 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53634601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com