user3054491
user3054491

Reputation: 51

Java create array of instance

I have problem with my code here

Seller[] seller = new Seller[numberOfSellers];           // Declared global

// Some operations here

seller[i].setJoinDate(joinDate);
seller[i].setNumberOfPost(numberOfPost);
seller[i].setCustomerReview(customerReviewCount);
seller[i].setSafeTag(safeTag);

Then I have this Seller class with these methods

public void setJoinDate( String joinDate ) { this.joinDate = joinDate; }

public void setNumberOfPost( int numberOfPost ) { this.numberOfPost = numberOfPost; }

public void setCustomerReview( int customerReview ) { this.customerReview = customerReview; }

public void setSafeTag( String safeTag ) { this.safeTag = safeTag; }

Above is the shortened code of mine. If it is unclear please do point me where.

Basically I creating an array of instance. Then I will set the data.

Assuming the joinDate,numberOfPost,customerReviewCount,safeTag and lastly the numberOfSellers has no problem with is which it is.

The problem I had is at the setting of the data to the instance. Which is the setJoinDate,setNumberOfPost,setCustomerReview,setSafeTag. Anyone can help me detect my error here?

When I execute the program, it gives me this error

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
at fyp.draft.pkg1.Design.actionPerformed(Design.java:247)

Upvotes: 0

Views: 136

Answers (4)

shikjohari
shikjohari

Reputation: 2288

I think your number numberOfSellers is initialised to 0 as the error says.

You can try the following piece of code;

int numberOfSellers = 3;
Seller[] seller = new Seller[numberOfSellers];           // Declared global

for(int i = 0 ; i<seller.length ; i++){
seller[i] = new Seller();
seller[i].setJoinDate(joinDate);
seller[i].setNumberOfPost(numberOfPost);
seller[i].setCustomerReview(customerReviewCount);
seller[i].setSafeTag(safeTag);
}

Upvotes: 0

Andremoniy
Andremoniy

Reputation: 34900

Because of index equals 0 from provided exception, it seems that your variable numberOfSellers also equals 0. That means, that your array seller is always empty.

BTW There is no term global in Java. May be you mean that your array is static field of Class or just object variable (field)?

Upvotes: 1

zhujik
zhujik

Reputation: 6574

numberOfSellers doesn't seem to be set or equals zero at the time you run the code. example:

  public static int b;

  public static void main(String[] args) {

    Double[] d = new Double[b];

    d[5].doubleValue();
  }

leads to

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

Upvotes: 2

Michael A
Michael A

Reputation: 5840

You need to initiallize the array:

 for(int i=0;i<numberOfSellers;i++)
 { 
    seller[i] = new seller();
 }

Upvotes: -1

Related Questions