Java 使用 toString 函数返回时出错

Java Error on returning with a toString function

我对 Java 还很陌生,到目前为止只用它编程了几个月。

我有两个 class,TimeSlotLabGroup

TimeSlotclass中有代码--

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]);  
}

然后在LabGroup class中有代码--

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 方法--

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

但是我得到了--

Group AlabExam1.TimeSlot@3f0fbfe5
, Group BlabExam1.TimeSlot@ea0e8b8
, Group ClabExam1.TimeSlot@25eab2ba
, Group DlabExam1.TimeSlot@37528b33

您在 class LabGroup 中提供了 toString() 方法 - 该方法有效(但存在一些小问题)。问题是您没有在 class TimeSpec.

中提供方法 toString()


当你做 return "Group "+ charLabel + timeSpec+ "\n"; 你告诉程序 return 你的对象 timeSpec 作为一个字符串。
所以基本上它会调用你的 TimeSlot toString 函数,return 是你的TimeSlot@3f0fbfe5 (ClassName@HashCode)。 您需要做的是 override TimeSlot 的 toString,以便在调用它时以您选择的格式给出一个字符串。 希望对你有帮助。

您需要重写 toString 方法,因为如果您打印 charLabel 它将简单地调用 Object class 中的 toString 方法 returns return getClass().getName() + "@" + Integer.toHexString(hashCode());

因此,您需要执行以下任一操作:

1) 像这样在 TimeSlot 中实现 toString 方法:

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

2) 修改LabGroup toString方法如下,在TimeSlot

中引入getter方法
public String toString() {
    return "Group " + charLabel.getDay() + " " + charLabel.getStart() + " - " + charLabel.getEnd();

}