when I go to print out the array, it prints the value for the last object called for. How can i get it to print out the different objects in the array? I think there is an error in the method I use to call upon the location of the object's variables stored in the array.
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;}
}
The problem might be in how you are defining your class variables. In your EventInformation
class you are defining them as static:
static String eventTime;
static int eventDatum;
This means there will only be ONE copy of each of these variables no matter how many EventInformation instances you create (ie they will all share the same copy).
Try removing the static
keyword from the variable declarations to see if that resolves your issue.