下面是一个程序,我需要将 String time 和 int datum 作为对象存储在数组中,然后将它们打印出来。这就是我目前要做的事情。我相信这是我的 recordEvent 方法的问题。
class RecordEvents4 {
public static void main(String[] args){
Recorder4 r1 = new Recorder4(100,100,"Wombat Detection");
r1.recordEvent("10:53",20);
r1.recordEvent("10:59",20);
r1.recordEvent("11:05",20);
r1.recordEvent("12:59",10);
r1.recordEvent("13:59",10);
r1.recordEvent("14:06",10);
r1.printEvents();
}
}
class Recorder4 {
int xPos, yPos;
String eventType;
EventInformation[] event = new EventInformation[10];
int xevent = 0;
final int EVENT_MAX = 10;
Recorder4(int xPos, int yPos, String eventType){
this.xPos = xPos;
this.yPos = yPos;
this.eventType = eventType;
}
public void recordEvent(String time, int datum){
/*for(int i = 0; i<event.length; i++){
event[i] = new EventInformation(time, datum);
}*/
event[xevent] = new EventInformation(time, datum);
xevent++;
if(xevent > EVENT_MAX){
System.out.println("Event log overflow - terminating");
System.exit(1);
}
}
void printEvents(){
System.out.println("Record of " + eventType + " events at [" + xPos + "," + yPos + "]");
for(int i = 0; i < xevent; i++){
System.out.println("Event number " + i + " was recorded at " + event[i] + " with datum = " + event[i]);
}
}
}
class EventInformation {
String eventTime;
int eventDatum;
EventInformation(String eventTime, int eventDatum){
this.eventTime = eventTime;
this.eventDatum = eventDatum;
}
}
这就是它的输出:
Record of Wombat Detection events at [100,100]
Event number 0 was recorded at EventInformation@15db9742 with datum = EventInformation@15db9742
Event number 1 was recorded at EventInformation@6d06d69c with datum = EventInformation@6d06d69c
Event number 2 was recorded at EventInformation@7852e922 with datum = EventInformation@7852e922
Event number 3 was recorded at EventInformation@4e25154f with datum = EventInformation@4e25154f
Event number 4 was recorded at EventInformation@70dea4e with datum = EventInformation@70dea4e
Event number 5 was recorded at EventInformation@5c647e05 with datum = EventInformation@5c647e05
这就是我所期待的:
Record of Wombat Detection events at [100,100]
Event number 0 was recorded at 10:53 with datum = 20
Event number 1 was recorded at 10:59 with datum = 20
Event number 2 was recorded at 11:05 with datum = 20
Event number 3 was recorded at 12:59 with datum = 10
Event number 4 was recorded at 13:59 with datum = 10
Event number 5 was recorded at 14:06 with datum = 10
有人建议我使用 toString() ,但我不确定使用 recordEvent() 的方向是否正确,我打算将方法参数分配给 EventInformation 对象,该对象的引用是存储在事件数组的元素中。
最佳答案
您实际上是在要求 Java 打印出事件数组的一个元素。在此数组的声明中,您为其中的元素指定了 EventInformation
类型。默认情况下,Java 显然不知道如何打印它,因为你自己定义了它!要解决此问题,请更改打印语句:
System.out.println("Event number " + i + " was recorded at " + event[i].eventTime + " with datum = " + event[i].eventDatum);
现在您要求 Java 打印 eventTime
(字符串)和 eventDatum
(整数)。这些都是 Java 知道如何打印的东西,因为它们是由 Java 本身定义的。
关于java - 程序不返回数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46543037/