2017-11-25 247 views
0

我對Java相當陌生,至今只用了幾個月的時間編程。使用toString函數返回時的Java錯誤

我有兩個類,TimeSlotLabGroup

TimeSlot類有在LabGroup類的代碼 -

private Time start; 
private Time end; 
private String day; 

public TimeSlot(String spec) { 
    //splits given string on each space 
    String[] splitSpec = spec.split(" "); 
    day = splitSpec[0]; 

    //uses the class Time, and passes in the hour and the minute of the time the lab begins. 
    this.start = new Time(splitSpec[1]); 

    //uses the class Time, and passes in the hour and the minute of the time the lab finishes. 
    this.end = new Time(splitSpec[2]); 
} 

然後是代碼 -

public String charLabel; 
public TimeSlot timeSpec; 
public String lineTime; 

public LabGroup(String line) { 

    String[] lineSplit = line.split(" "); 
    charLabel = lineSplit[0]; 

    //string a = "Day StartTime EndTime" 
    String a = lineSplit[1] + " " + lineSplit[2] + " " + lineSplit[3]; 

    timeSpec = new TimeSlot(a); 


} 

toString method--

public String toString() { 
    return "Group "+ charLabel + timeSpec+ "\n"; 

} 
沿

輸入到LabGroup的示例將是"A Mon 13:00 15:00"然後應該給輸出,通過toString,中 -

Group A Mon 13:00 - 15:00 
Group B Mon 15:00 - 17:00 
Group C Tue 13:00 - 15:00 
Group D Tue 15:00 - 17:00 

但是,相反我在班級LabGroup getting--

Group [email protected] 
, Group [email protected] 
, Group [email protected] 
, Group [email protected] 

回答

0

你需要重寫toString方法,因爲如果要打印charLabel它只是調用toString方法Object類,所以返回return getClass().getName() + "@" + Integer.toHexString(hashCode());

,你需要做的要麼以下:

1)實施toString方法在TimeSlot這樣的:

public String toString() { 
    return day + " " + start + " - " + end; 
} 

2)修改LabGrouptoString方法如下通過引入吸氣方法在TimeSlot

public String toString() { 
    return "Group " + charLabel.getDay() + " " + charLabel.getStart() + " - " + charLabel.getEnd(); 

} 
0

您提供了toString()方法 - 這種方法作品(有一些小問題)。問題是你沒有在TimeSpec類中提供方法toString()。

0


當你做return "Group "+ charLabel + timeSpec+ "\n";你告訴程序返回你的對象timeSpec作爲一個字符串。
所以基本上它會調用你的TimeSlot toString函數,它返回你的[email protected][email protected])。 你需要做的是override TimeSlot的toString,這樣當它被調用時,它會以你選擇的格式給出一個字符串。 希望它有幫助。