這是實驗室的一部分,我找不出來......我無法弄清楚名單類中的addGrade方法有什麼問題,我必須給學生添加一個成績,如果學生尚不存在,創建一個新學生,然後添加成績。請注意,最初,這個類沒有實例變量Student stu,我試圖讓事情起作用時添加了它。爲什麼我無法將元素添加到Java中的LinkedList中?
學生提供了一個構造函數,學生成績保存在一個鏈表中。我只把代碼的一部分放在這裏......它有一些方法來獲得學生的名字,獲得分數,增加分數,並獲得平均分數。
我的代碼在經過一些編輯後不再有效......當它部分工作時,它只是覆蓋了以前的最新版本的學生。學生a添加了5年級,然後學生b添加了7,然後學生a再次添加了10.這應該讓學生a在鏈接列表中有2個條目(5,10)。當我運行我的代碼時,它只有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();
}
}
現在,讓我們開始 「工作」 的定義。代碼的工作原理是什麼?什麼部分特別是造成你的麻煩? – Makoto
你可能想在'Roster'中(或者是一個人的類:p)想要一個'Student'的List。請注意,使用學生姓名作爲鍵和學生作爲價值的「地圖」在這裏可能非常方便(更容易檢查現有學生)。 –
你可能想要一個'Map分數而不是鏈接列表(將課程映射到分數)。 –
alfasin