【问题标题】:Java Error on returning with a toString function [duplicate]使用 toString 函数返回时出现 Java 错误 [重复]
【发布时间】:2018-05-09 04:22:03
【问题描述】:

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

我有两个班级,TimeSlotLabGroup

TimeSlot 类中有代码--

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 类中有代码--

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

【问题讨论】:

    标签: java class printing tostring


    【解决方案1】:

    您需要覆盖toString 方法,因为如果您打印charLabel,它只会调用Object 类中的toString 方法,该方法返回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();
    
    }
    

    【讨论】:

      【解决方案2】:

      您在 LabGroup 类中提供了 toString() 方法 - 此方法有效(存在一些小问题)。问题是你没有在 TimeSpec 类中提供 toString() 方法。

      【讨论】:

        【解决方案3】:


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

        【讨论】:

          猜你喜欢
          • 2019-07-08
          • 2013-06-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-28
          • 2021-12-22
          • 1970-01-01
          相关资源
          最近更新 更多