当我去打印数组时,它会打印最后一个调用的对象的值。我怎样才能让它打印出数组中的不同对象?我认为我用来调用存储在数组中的对象变量的位置的方法中存在错误。class Recorder4 {int xPos, yPos;String eventType;final int EVENT_MAX = 10;EventInformation[] event = new EventInformation [EVENT_MAX]; //this is the arrayint xevent = 0;Recorder4 (int xPos, int yPos, String eventType) { this.xPos = xPos; this.yPos = yPos; this.eventType = eventType;}public void recordEvent (String Time, int Datum) { if (xevent <= EVENT_MAX) { event[xevent] = new EventInformation(Time, Datum); xevent++; //this is where new instances of the object are assigned a place in the array } else {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].getTime() //i think these methods is where the issue lies + " with datum = " + event[i].getDatum()); } }}class EventInformation {static String eventTime;static int eventDatum;EventInformation (String s, int i) { eventTime = s; eventDatum = i;} public int getDatum() { return EventInformation.eventDatum;} public String getTime() { return EventInformation.eventTime;} }
1 回答
繁星点点滴滴
TA贡献1803条经验 获得超3个赞
问题可能在于您如何定义类变量。在您的EventInformation课程中,您将它们定义为静态:
static String eventTime;
static int eventDatum;
这意味着无论您创建多少个 EventInformation 实例(即它们都将共享相同的副本),这些变量中的每一个都将只有一个副本。
尝试static从变量声明中删除关键字,看看是否能解决您的问题。
添加回答
举报
0/150
提交
取消