-4
String[] array; 
int i = 0; 
for(Element link : listOfLinks) { 
    array[i++] = link.text(); 
} 

This is the code i'm trying to fill my array.

The error is that in the line: array[i++] = link.text(); the word 'array' is highlighted and there is written: "The local variable array may not have been initialized"

Ivan Gorbunov
  • 11
  • 1
  • 1
  • 4
  • 5
    you never initialized your string array. Like how you initialized `i`, `array` needs to be initialized too. Remember, all variables have to be initialized before being used. `String[] array = new String[100];` for example – Chris Gong Dec 13 '16 at 20:40
  • first initialize your array, `String[] array = new String[listOfLinks.size()];` – Priyam Gupta Dec 13 '16 at 20:43
  • You need to read up what is a class variable, instance variable and local variable. – user3437460 Dec 13 '16 at 20:44

3 Answers3

1

You need to initialize the array.

String[] array = new String[X];

X being the size of the array.

1

That is correct. All you have done is define a variable, array, which can hold a reference to an array object.

As it stands, your array has not been instantiated and initialised.

You need to specify the size of your array. E.g. by changing your first line to...

String[] array = new String[listOfLinks.size()]

This will instantiate the array and initialize all its elements to null.

Cave Johnson
  • 6,499
  • 5
  • 38
  • 57
Baz Cuda
  • 41
  • 6
0

You need to initialize an array of object, setting the dimension first. For example:

String[] array =  new String[10];

If you need a dynamic array, I suggest using an ArrayList of Strings:

ArrayList<String> array = new ArrayList<String>();
dWinterDev
  • 44
  • 2