"Non-static method cannot be referenced from static context"错误



我想做的是在这里添加来自另一个类(Noten)的对象并将它们打印出来。我知道这是一个常见的问题,但我仍然找不到解决方案。

private ArrayList<Noten> notes123;
public void addNotes(Noten newNotes) {
    if (notes123.size() >= 0) {
        notes123.add(newNotes);
        System.out.println(newNotes);
    } else {
        System.out.println("No Notes.");
    }
}
public void schuelerInfo() {
    System.out.println("Name: " + name + " Student number: " + nummer);
    System.out.println("The notes are ");
    for (Noten note: notes123) {
        System.out.println(Noten.notenInfo());
    }
}

从更改for循环

for (Noten note : notes123){
   System.out.println(Noten.notenInfo());
}

for (Noten note : notes123){
   note.notenInfo();
}

由于noteInfo方法被定义为非静态方法,您正试图使用Noten(类)静态访问它。您只能在arraylist中已经存储了引用的对象上访问它。

由于notenInfo()不是静态方法,因此必须在Noten对象的实例上调用它。例如:

Noten n = new Noten();
n.notenInfo();

相关内容

最新更新