在覆盖 toString() 后,我在打印出对象时遇到了一些问题。在不覆盖 toString() 的情况下,我可以打印出对象引用而不会出现任何错误。但是,当我尝试覆盖 toString() 方法时,我只能打印出一些输出(大约 30 个输出中的 10 个),而另一些则给出错误。
错误是:
Exception in thread "main" java.lang.NullPointerException
at Airline.toString(AirlineMain.java:277)
at java.lang.String.valueOf(String.java:2902)
at java.io.PrintStream.println(PrintStream.java:821)
at AirlineMain.main(AirlineMain.java:432)
基本上我有一个名为“Airline”的类,并且正在创建对象并将其存储到ArrayList<Airline>
.
Airline 类构造函数:
public Airline(String fromCity, String toCity, SGTime departTime,
int arriveDay, SGTime arriveTime, int cost) {
this.fromCity = fromCity;
this.toCity = toCity;
this.departTime = departTime;
this.arriveDay = arriveDay;
this.arriveTime = arriveTime;
this.cost = cost;
}
SGTime 构造函数:
public SGTime(int hour, int min) {
this.hour = hour;
this.min = min;
}
我对 toString() 的覆盖:
public String toString() {
return getFromCity() +" "+ getToCity()+" "+getDepartTime().getHour()+":"+getDepartTime().getMin()+" "+getArriveDay()+" "+getArriveTime().getHour()+":"+getArriveTime().getMin()+" "+getCost();
}
所有实例属性都定义了访问器。例子:
public String getFromCity (){
return fromCity;
}
提前感谢您的任何指导!