[英]Printing Out Object In Java
我有一個file
,其中包含以下內容:
5
Derrick Rose
1 15 19 26 33 46
Kobe Bryant
17 19 33 34 46 47
Pau Gasol
1 4 9 16 25 36
Kevin Durant
17 19 34 46 47 48
LeBron James
5 10 17 19 34 47
我試圖在票證構造函數中將票證的名稱和數字放在一個數組中,但是當我實例化我的票證對象並嘗試顯示它時,我得到以下內容:
Tickets: lottery$Ticket@33909752
Tickets: lottery$Ticket@55f96302
Tickets: lottery$Ticket@3d4eac69
Tickets: lottery$Ticket@42a57993
Tickets: lottery$Ticket@75b84c92
在我的構造函數中是否存在問題,或者如果不首先將其作為字符串打印,是否無法打印數組?
int lim = scan.nextInt();
scan.nextLine();
for(int i = 0; i < lim; i++)
{
String name = scan.nextLine();
String num = scan.nextLine();
String[] t = num.split(" ");
int[] tichold = new int[t.length];
for(int j = 0; j < t.length; j++)
{
tichold[j] = Integer.parseInt(t[j]);
}
Ticket ticket = new Ticket(name, tichold);
System.out.println("Ticket: " + ticket);
}
scan.close();
}
public static class Ticket
{
public String name;
public int[] tarray;
public Ticket(String name, int[] tarray)
{
this.name = name;
this.tarray = tarray;
}
}
您需要為它提供toString
方法。 以下是您可以使用的示例:
@Override
public String toString() {
return "Ticket{" +
"name='" + name + '\'' +
", tarray=" + Arrays.toString(tarray) +
'}';
}
為了實現這一點,你需要編寫一個重疊的toString方法並在那里寫入你想要的東西。
public String toString(){
return //whatever you need goes here and will be printed when you try and
//print the object
}
您必須覆蓋從Object類繼承的toString方法:
@Override
public String toString(){
return //Enter the format you require
}
記住故障單是一個引用變量,因此當您將其打印出來時,您將獲得哈希碼以及該對象所屬的類的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.