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());
}
}
If the compiler believes that a local variable might not have been initialized before the next statement which is using it, you get this error. You will not get this error if you just declare the local variable but will not use it.
This error occurs only for local variables since Java automatically initializes the instance variables at compile time (it sets 0 for integers, false for boolean, etc.). However, local variables need a default value because the Java compiler doesn't allow the use of uninitialized variables.
Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With