Array variable “might not have been initialized”

后端 未结 2 594
别那么骄傲
别那么骄傲 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.

    0 讨论(0)
  • 2021-01-05 23:11

    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

    0 讨论(0)
提交回复
热议问题