数组不打印不同的对象

array not printing different objects

当我打印数组时,它打印了最后一个调用的对象的值。我怎样才能让它打印出数组中的不同对象?我认为我用来调用存储在数组中的对象变量位置的方法有错误。

class Recorder4 {

int xPos, yPos;
String eventType;
final int EVENT_MAX = 10;
EventInformation[] event = new EventInformation [EVENT_MAX]; //this is the array
int 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;}

 }

问题可能在于您定义 class 变量的方式。在您的 EventInformation class 中,您将它们定义为静态的:

static String eventTime;
static int eventDatum;

这意味着无论您创建多少个 EventInformation 实例,每个变量都只有一个副本(即它们将共享同一个副本)。

尝试从变量声明中删除 static 关键字,看看是否能解决您的问题。