Array variable “might not have been initialized”

后端 未结 2 616
别那么骄傲
别那么骄傲 2021-01-05 22:11

I get the error:

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

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-05 22:57

    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.

提交回复
热议问题