2012-11-13 70 views
1

我有一個項目,我面臨着我再次遇到的一個問題。打印對象並獲取Java中的具體內容

我們給出了這個測試儀文件。不應該編輯它。 我希望你把重點放在這一行:

System.out.println(bb) ; 

它打印的對象吧?

import java.util.Arrays ; 
/** 
    Presents some problems to the BillBoard class. 
*/ 
public class BillboardTester 
{ 
    public static void main(String[] args) 
    { 
    int[] profits = new int[]{1, 2, 3, 1, 6, 10} ; 
    int k = 2 ; 
    System.out.println("Profits: " + 
       Arrays.toString(profits) + " k = " + k) ; 
    Billboard bb = new Billboard(profits, k) ; 
    System.out.println("Maximum Profit = " + bb.maximumProfit()) ; 
    System.out.println(bb) ; 

    k = 3 ; 
    profits = new int[]{7, 4, 5, 6, 1, 7, 8, 9, 2, 5} ; 
    System.out.println("Profits: " + 
       Arrays.toString(profits) + " k = " + k) ; 
    bb = new Billboard(profits, k) ; 
    System.out.println("Maximum Profit = " + bb.maximumProfit()) ; 
    System.out.println(bb) ; 
    } 
} 

然後通過打印對象,他希望這樣的結果:

Billboards removed (profit): 3(1) 0(1) => profit loss of 2 
total value of billboards = 23 
remaining maximum profit = 21 

我不知道我有什麼方法在實際的廣告牌類來創建,所以我能得到這個打印出來。你有什麼建議嗎?我想知道這背後的邏輯,而不是解決這個特定問題。

+0

你想要什麼打印? –

回答

4

重寫toString方法。

無論何時打印班級的任何實例,都會調用toString方法。如果您不覆蓋它,將使用Object'stoString,它將返回一個表示形式,其格式爲[email protected]

要打印您自己的表示法,請覆蓋它,然後調用toString的實現。

@Override 
public String toString() { 
    return this.getProfit(); 
} 

您可以相應地改變你的返回的字符串。我不知道你的k是什麼,但你也可以在你的returned string中加入。

+0

我可以請一個簡單的例子嗎?我對此很新。謝謝... –

+0

@MikeSpy ..我剛剛發佈了一個。 –

+0

非常感謝Rohit Jain!這正是我所期待的! –

4

重寫toString方法。打印對象依賴於Object類中定義的方法。通過覆蓋它,你的實現將被用來代替那個。

考慮println的文檔:

打印Object,然後終止該行。此方法首先調用 String.valueOf(x)以獲取打印對象的字符串值,然後 的行爲就像調用print(String)然後println()。

println依靠String.valueOf(x)誰調用xtoString方法。

一個例子:

public String toString() { 
    return "Billboards removed (profit):" + someParam + " => profit loss of " + 
      profitLoss + "\ntotal value of billboards = " + totalValue + 
      "\nremaining maximum profit = " + remainingProfit; 
} 

長話短說,你可以返回你的對象,你「描述」其內容的String表示。如果你有一個Person對象,你toString會,也許,是這樣的:

"Name: " + personName + "Email: " + personEmail. 
+0

非常感謝Gamb!這很好,你也給了我這個例子的回報!決定誰給出正確的答案是非常困難的。你們兩個在解釋我的時候都做得很出色......但我想我會把它交給羅希特·賈因,因爲他是第一個讓我明白的人。但是,謝謝!我很感激... –

+0

@MikeSpy沒有汗!這裏重要的是你必須理解它。保持良好的工作。 – Gamb

+0

謝謝Gamb! :) –