public class Array
{
public int dimensione;
public int[] arr;
/*
* n: array dimension
*/
public Array(int n)
{
dimensione = n;
int max = 10;
int min = 1;
int[] arr = new int[n];
//put random number between 1 and 10 in the array
for(int i = 0; i < n; i++)
{
arr[i] = (int)(Math.random() * ((max - min) + 1) + min);
}
}
public String toString()
{
String arrayToString = "";
for(int i = 0; i < dimensione; i++)
{
arrayToString = arrayToString + arr[i] + " ";
}
return arrayToString;
}
}
I have this code and i get the error but i don’t understand why. Is the array not being filled correctly and it stays null so when i try to write it as a string it finds a null array? if yes, why is not working? how do i solve it?
>Solution :
In the constructor, you declare a local variable arr which shadows the class’s arr field, which remains null. That causes a NullPointerException when you call toString (which you apparently do somewhere).
Change
int[] arr = new int[n];
to
arr = new int[n];