打印对象

时间:2019-07-25 10:31:08

标签: java

我想打印出对象的单个值,说我只想打印一个对象的名字,而不是所有对象的名字,我该怎么做?您会在代码中看到我从未给对象命名,所以我将如何引用它们?

我已经添加了字符串覆盖方法。

我不确定对象的名称是什么,因此我无法单独引用它们。

我和学生对象有一个单独的类,而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);
     }

无法静态引用非静态字段。

2 个答案:

答案 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);关键字的文档,它的含义以及使用方法。我建议您阅读此书,因为它可以帮助您理解此问题,并防止将来犯同样的错误。