当我要打印出数组时,它会打印出所需要的最后一个对象的值。我怎样才能打印出数组中的不同对象?我认为调用存储在数组中的对象变量的位置的方法中存在错误。
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;}
}
答案 0 :(得分:0)
问题可能出在您如何定义类变量。在EventInformation
类中,您将它们定义为静态:
static String eventTime;
static int eventDatum;
这意味着,无论您创建多少个EventInformation实例,每个变量都将只有一个副本(即,它们将共享同一副本)。
尝试从变量声明中删除static
关键字,看看是否可以解决您的问题。