0

I have this class its basically a university system on which a student can post different kind of posts and people can reply to there posts.

Event is a kind of post

public class Event extends Post {
    private String Venue;
    private String Date;
    private int Capacity;
    private int AttendeeCount;
    String[] Attendee_list=new String[getCapacity()]


    public Event(String Id,String Title,String desc,String CreatorID,String Venue, String Date, int Capacity)
    {
        //ID i.e eventID and CreatorID are auto created
        super(Id,Title,desc,CreatorID);
        this.Venue=Venue;
        this.Date=Date;
        this.Capacity=Capacity;
        AttendeeCount=0;
    }

i am trying to implement this method.

where reply.getResponderID() basically gets responder id of reply on post.

when i am trying to add the responder it to the attendee list of the event after it passes the if() condition it is throwing an arrayindexoutofbound exception.

    @Override
    public boolean handleReply(Reply reply)
    {
            if (AttendeeCount < Capacity & !(Arrays.asList(Attendee_list).contains(reply.getResponderID())))
            {
                Attendee_list[AttendeeCount]=reply.getResponderID();
                getReplyCollection().add(reply);
                AttendeeCount++;
                return true;
            }
        return false;
    }

I can't figure out why???

Ayush Ranjan
  • 101
  • 5
  • Time to use your debugger to find out why your program is misbehaving – Hovercraft Full Of Eels Mar 29 '20 at 12:37
  • A clue: AttendeeCount is greater than or equal to what getCapacity() returned. – rghome Mar 29 '20 at 12:39
  • 1
    Put this `this.Attendee_list = new String[getCapacity()];` as the last line in your constructor. Otherwise it will be initialized before `this.Capacity` is set (and still has default value `0`). [Instance fields are initialized sooner than constructor](https://farenda.com/java/java-initialization-order/). – Šimon Kocúrek Mar 29 '20 at 12:39
  • Check the size of the array. – NomadMaker Mar 29 '20 at 12:40
  • Also, java naming conventions have classes begin with capital letters, and methods and variables beginning with lower case letters. This makes identifiers easier to identify when debugging. – NomadMaker Mar 29 '20 at 12:41
  • Also, why is this question closed as duplicate? This is clearly not answered by [linked question](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it). – Šimon Kocúrek Mar 29 '20 at 12:43
  • 1
    @ŠimonKocúrek thanks ```this.Attendee_list = new String[getCapacity()];``` solved my problem – Ayush Ranjan Mar 29 '20 at 21:32

0 Answers0