2017-11-25 248 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,这样当它被调用时,它会以你选择的格式给出一个字符串。 希望它有帮助。