数组不打印不同的对象

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


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;}


 }


临摹微笑
浏览 102回答 1
1回答

繁星点点滴滴

问题可能在于您如何定义类变量。在您的EventInformation课程中,您将它们定义为静态:static String eventTime;static int eventDatum;这意味着无论您创建多少个 EventInformation 实例(即它们都将共享相同的副本),这些变量中的每一个都将只有一个副本。尝试static从变量声明中删除关键字,看看是否能解决您的问题。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java