-5

mhey i have to do the following to my code below and not sure how to correctly get it to just print Event log overflow - terminating once. its printing multiple times.

To do: the length of the array event is specified with a constant (a final int) called EVENT_MAX ii. the method recordEvent checks that there is room remaining in the array event to store another event (hint: compare xevent and EVENT_MAX). If there is not then the message: Event log overflow - terminating should be output and the program terminated with the following method call: System.exit(1);

class RecordEvents2 {
   public static void main (String args[]) {
      Recorder r1 = new Recorder (100,100,"Wombat Detection");
      r1.recordEvent("10:53");
      r1.recordEvent("10:59");
      r1.recordEvent("11:05");
      r1.recordEvent("12:59");
      r1.recordEvent("13:50");
      r1.recordEvent("14:06");
      r1.printEvents();
   }
}

class Recorder {
   int xPos,yPos;
   String eventType;
   String [] event = new String [5];
   final int EVENT_Max = 0;
   
   int xevent = 0; 
   
   Recorder (int xPos, int yPos, String eventType ) {
      this.xPos = xPos;
      this.yPos = yPos ;
      this.eventType = eventType;
   }
   
   void recordEvent (String eventTime ) {
      event [xevent] = eventTime;
      xevent++;
      if (xevent > EVENT_Max){
         System.out.println ("Event log overflow - terminating");
      }
   }
   void printEvents(){
      System.out.println ("Record of " + eventType +
            " events at [" + xPos + "," + yPos + "] " );
      int index=0;
      for (String current: event) {
         if (xevent > index){
            String ss=String.format("Event number %s was recorded at ",index);
            System.out.println(ss + current);
            index++;  
         }
      }      
   }
}
L.N
  • 13
  • 6

1 Answers1

5

You are initializing the array with size 5 but you are inserting 6 elements. So the last insertion is out of bounds of the array

You could add a expandArray function that get's called and then add existing elements into that new array. Or you can use an ArrayList

Norsk
  • 622
  • 1
  • 10
  • 22