下面是一些命令的println缺少在main方法的代碼本身我的ArrayList不會承認什麼,我添加到列表中
import java.util.ArrayList;
public class Student {
private String name;
private int age;
public Student (String n, int a) {
name = n;
age = a;
}
public String toString() {
return name + " is " + age + " years old";
}
ArrayList<Student> rayList = new ArrayList<Student>();
rayList.add(new Student("Sam", 17));
rayList.add(new Student("Sandra", 18));
rayList.add(new Student("Billy", 16));
rayList.add(new Student("Greg", 17));
rayList.add(new Student("Jill", 18));
public static void main(String[] args) {
System.out.println(rayList.get(0));
}
}
。 但是,當我嘗試了5名學生加入到我的ArrayList中,我得到錯誤「不能讓一個靜態引用非靜態字段rayList」
你已經解決了這個問題(有2個),但只解釋了爲什麼它被破壞的一部分,而不是OP詢問的部分。不,靜態初始化器和方法不是可以執行代碼的唯一上下文。也有實例初始化器。 – Nicole
@NickC第一感謝實例初始化者,第二,你能解釋「而不是OP詢問的問題」嗎?正如我所看到的,OP不知道爲什麼他們的代碼出錯,這是因爲執行上下文...... – MadProgrammer
在我看來,編譯器發現的第一個錯誤是'rayList'不是靜態的但是從靜態方法'main'引用。我認爲OP也應該知道這一點,但重要的是你也發現了另一個錯誤。 – Nicole