我想打印出对象的单个值,说我只想打印一个对象的名字,而不是所有对象的名字,我该怎么做?您会在代码中看到我从未给对象命名,所以我将如何引用它们?
我已经添加了字符串覆盖方法。
我不确定对象的名称是什么,因此我无法单独引用它们。
我和学生对象有一个单独的类,而readFile方法正在读取文本文件并创建一个新对象。
那么我该如何使用system.out.println
来引用这个对象?
public static boolean readFile(String filename)
{
File file = new File(filename);
try
{
List<Student> list = new ArrayList<>();
Scanner scanner = new Scanner(file);
while(scanner.hasNextLine())
{
String[] words = scanner.nextLine().split(",");
list.add(new Student(words[0],words[1],words[2], new String[ {words[3],words[4],words[5],words[6],words[7]} ]);
}
}
catch (FileNotFoundException e)
{
System.out.println("Failed to read file");
}
return true;
}
public static void main(String[] args)
{
readFile("C:\\temp\\studentdata.txt");
displayMenu();
}
private static void displayReportByMarks()
{
System.out.println(Student.id);
}
无法静态引用非静态字段。
答案 0 :(得分:0)
似乎Student
有一个成员id
。该成员属于类Student
的 instance ,而不属于类本身。您无法访问
Student.id
答案 1 :(得分:0)
假定标准大写规则:
Student
是一个类(即数据类型)。呼叫Student.id
时,是指id
的{{1}},而不是特定的Student
(注意大写)。
如果要打印特定学生的ID,则需要对其的引用。有几种方法可以做到这一点:
student
的一个实例传递给您的Student
函数,使其变为displayReportByMarks()
displayReportByMarks(Student student)
的列表并致电Student
list.forEach(s -> System.out::println(s.id));
您的代码还有其他问题,但这是给您的错误“无法静态引用非静态字段”。
我建议您阅读:https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html。这是Oracle关于for (Student student : list) System.out.println(student.id);
关键字的文档,它的含义以及使用方法。我建议您阅读此书,因为它可以帮助您理解此问题,并防止将来犯同样的错误。