簡體   English   中英

來自另一個類的Java println方法

[英]Java println method from another class

我對另一個類的方法有問題

我要的方法是:

/**
 * Prints out information about the owner
 */
public void printOwnerInfo()
{
    System.out.println("Information about the owner of the forest");
    System.out.println("Name: " + name);
    System.out.println("Adresse: " + adresse);
    System.out.println("Phone Number: " + phone);
}

我想在旁邊打印此信息:

/**
 * Prints out information about the forest
 */
public void printForestInfo()
{
    System.out.println("Information about forest: " + name);
    System.out.println("Location: " + location);
    System.out.println("Square meters: " + squareMeters);
    System.out.println("Price per square meter: " + price + " euro");
    System.out.println("Price for the forest: " + (squareMeters * price) + " euro");
    System.out.println.forestOwner.printOwnerInfo();
}

我在“森林”字段中將“所有者”類聲明為:

public Owner forestOwner;

但是我似乎無法用林信息打印出所有者信息。 他們每個人都能很好地工作。

這沒有道理

System.out.println.forestOwner.printOwnerInfo();

我猜你想從對象forestOwner打印方法printOwnerInfo()所以:-

forestOwner.printOwnerInfo();

它將在對象上調用方法,並在Println處理Println

該調用沒有意義:

System.out.println.forestOwner.printOwnerInfo();

僅當printOwnerInfo()返回一個String (然后將其傳遞到System.out.println調用中)並且更正了調用鏈時, printOwnerInfo()開始變得明智。 因此,用以下代碼替換該行:

forestOwner.printOwnerInfo()

...或者讓該所有者方法返回一個String ,然后像這樣調用它:

System.out.println(forestOwner.printOwnerInfo());

我認為您需要在printForestInfo方法中執行以下操作:

forestOwner.printOwnerInfo();

...當您的代碼從該方法中打印到控制台時。 System類的'out'字段聲明為static和public,因此在全局范圍內“可用”。

暫無
暫無

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

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