簡體   English   中英

打印對象

[英]Printing out objects

我想打印出我的對象的各個值。比如說我只想打印一個對象的名字,而不是所有對象的名字,我該怎么做?。 你會在代碼中看到我從來沒有給我的對象單獨的名字,那么我將如何引用它們?

我已經添加了字符串覆蓋方法的東西。

我不確定我的對象的名稱是什么,所以我不能單獨引用它們。

我有一個帶有學生對象的單獨類,而 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);
     }

不能對非靜態字段進行靜態引用。

似乎Student有一個成員id 該成員屬於Student類的一個實例,而不是類本身。 你無法訪問

Student.id

假設標准大寫規則:

Student是一個類(即數據類型)。 當您調用Student.id您指的是Studentid ,而不是特定的student (注意大小寫)。

如果要打印特定學生的 id,則需要對其進行引用 有幾種方法可以做到這一點:

  • Student的實例傳遞給displayReportByMarks()函數,使其變為displayReportByMarks(Student student)
  • 維護Student的列表並調用list.forEach(s -> System.out::println(s.id));
  • 與上面類似,調用for (Student student : list) System.out.println(student.id);

您的代碼還有其他問題,但這就是給您錯誤“無法對非靜態字段進行靜態引用”的原因。

我建議您閱讀: https : //docs.oracle.com/javase/tutorial/java/javaOO/classvars.html 這是 Oracle 關於static關鍵字、它的含義以及如何使用它的文檔。 我建議您閱讀本文,因為它會幫助您理解此問題並防止您將來犯同樣的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM