gpt4 book ai didi

java - 为什么我无法将元素添加到 Java 的 LinkedList 中?

转载 作者:行者123 更新时间:2023-12-01 11:38:42 25 4
gpt4 key购买 nike

这是我无法弄清楚的实验室的一部分...我无法弄清楚花名册类中的 addGrade 方法有什么问题,我必须在该方法中为学生添加成绩,并且如果学生尚不存在,请创建一个新学生,然后添加成绩。请注意,最初,此类没有实例变量 Student Stu,这是我在尝试让事情正常运行时添加的。

为学生提供一个构造函数,学生成绩保存在一个链接列表中。我在这里只放了一部分代码...它有获取学生姓名、获取分数、添加分数和获取平均分数的方法。

我的代码在经过一些编辑后不再工作...当它部分工作时,它只是用最新的代码覆盖了以前的学生。学生 a 添加了 5 年级,然后学生 b 添加了 7 年级,然后再次添加了学生 a 10 年级。这应该让学生 a 在链接列表中包含 2 个条目 (5, 10)。当我运行我的代码时,它只有学生 a 为 10,但也不能完全工作。

public class Student {
private String name;
private List scores = new LinkedList<>();

public Student(String name)
{
this.name = name;
}

public void addGrade(int score)
{
scores.add(score);
}


public class Roster {

String name;
int score;
Student stu;

//Adds a grade to the end of a list of grades for the named student.
//Should work even if no student with this name has ever been seen before.
public void addGrade(String name, int score) {
Student temp = new Student(name);
stu.addGrade(score);
}
//Gets the specified grade from the named student's scores.
public int getGrade(String name, int index) {
int a = stu.getScore(index);
return a;
}
//Gets the average for the named student.
public double getAverage(String name) {
return stu.getAverage();
}
}

最佳答案

花名册是学生列表。

学生有一个分数列表。

这不是您需要的全部代码,只是 Roster 类和其中的 addGrade() 方法的一部分:

public class Roster {
List<Students> students = new LinkedList<Student>();

public void addGrade(String name, int score) {
// Student s = null;
// Search for existing student.
for (Student currentStu : students) {
if (currentStu.name.equals(name) {
s = currentStu;
}
}

if (s == null) {
//Student not in our roster. Add him.
s = new Student(name);
}

// Add the score to that student.
s.addGrade(score);
}
}

关于java - 为什么我无法将元素添加到 Java 的 LinkedList 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29734929/

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