2012-11-13 24 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! :) –