C. E.
C. E.

Reputation: 10607

Array variable "might not have been initialized"

I get the error:

TestCounter.java:115: variable counters might not have been initialized counters[i] = new Counter(i);

And I can't figure out how to fix it. I know that my class, Counter, works. Below is my code, if you could have a look at it I would be very happy. This code is wrapped in the main method of a TestCounter class.

  if(success) 
  {  
   Counter[] counters;

   for(int i=0; i<30; i++)
   {
       counters[i] = new Counter(i);
       System.out.println(counters[i].whatIsCounter());
   }
  }

Upvotes: 5

Views: 11263

Answers (2)

Sid
Sid

Reputation: 4997

You need to initialize the counters array. Something like this:

if(success) 
  {  
   Counter[] counters=new Counters[30];

   for(int i=0; i<30; i++)
   {
       counters[i] = new Counter(i);
       System.out.println(counters[i].whatIsCounter());
   }
  }

By stating Counter[] counters you are not actually creating an array, you are simple declaring a reference variable counters of type Counter[].

Counter[] counters=new Counters[30] will create an array of type Counter of size 30 with each element holding null reference.

Upvotes: 0

skaffman
skaffman

Reputation: 403441

You haven't created the array, you've just declared the variable.

You need to do this:

Counter[] counters = new Counter[30];

or something similar

Upvotes: 13

Related Questions