user3502368
user3502368

Reputation:

Android/Java how to create an array of int

I have that code:

public int aNums[] = {};

And when i want add a number in my array enside a funcion i do that:

aNums[aNums.length]=num;

But the Aplication crash and exit.

Please help, thanks.

Upvotes: 0

Views: 136

Answers (3)

Alex Lungu
Alex Lungu

Reputation: 1114

You are trying to add the number at a position that doesn't exist. If you want it to be at the end of the array make sure to do this aNums[aNums.length-1]=num; Because the first element is at 0 and the last is at length-1

EDIT: For the last problem that you have you should do this: text.setText(String.valueOf(aNums.length)); This way you will get the length value as string

Upvotes: 1

Lokpati Tripathi
Lokpati Tripathi

Reputation: 34

public int aNums[] = {}; You have not initialized the integer array. To avoid your application getting crashhed. The best way to declare integer array is as show here.

public int array_name[]=new int[size_of_array];

now to add data inside the array.simply write array_name[position]=integer_data; where position should range from ( 0 and size_of_array-1).

Upvotes: 1

Junior Buckeridge
Junior Buckeridge

Reputation: 2085

You have a Java array instantiation problem. You're not declaring the array size. Try:

public int aNums[] = new int[ARRAY_LENGTH_HERE];

That should fix your problem.

Upvotes: 2

Related Questions