0

I have a problem I do not understand (probably very easy to solve).

int[] numbers;
numbers[0] = 0;

when I debug, the second line gets error:

"use of unassigned local variable"

How do I get rid of it?

pb2q
  • 58,613
  • 19
  • 146
  • 147

3 Answers3

2

You should first create/initialize an array of a certain length/size.

int[] numbers = new int[lenghtOfArray];

where lengthOfArray is an integer indicating the array's length/size.

Then you can have access to the items of the array using their index, as you do here:

numbers[0] = 0;

where you set the number 0 to the first item in the array, in the position with index 0.

Christos
  • 53,228
  • 8
  • 76
  • 108
0

Local variables aren't given a default value, and must be initialized before being read, and the compiler is complaining because you're using an unassigned local variable.

However the real problem with your code is that an array must be created/instantiated before being used.

You create it like any other object (here we'll create an array of 11 elements):

int[] numbers = new int[11];

An array is also an Object, and so numbers is a reference to an object, and must be instantiated to be used.

pb2q
  • 58,613
  • 19
  • 146
  • 147
0

You need to create the object before accessing.

When you say int[] numbers;, it just create a reference that can hold the real array. So here 'number' is a reference that can hold an int array.

In order to use/access it, you need to create the object by new keyword. That ll allocate memory of it.

So in order to use it, you need to do this : int[] numbers = new int[10];

Soumitri Pattnaik
  • 3,246
  • 4
  • 24
  • 42