I'm having a problem with a "java.lang.NullPointerException". The objective of this code is generate random numbers with an array with a specific size (in this case, 10 numbers, as given in the driver, but it doesn't matter), calculate the average, find the maximum, minimum and a specific number (as given in the driver, 2 and 3, but it doesn't matter). I think I could write all of this code with some research, but after everything done and compiled, I tried to run the code and for my surprise, I found the java.lang.NullPointerException. I had no idea of what it was, but with some research I learned and (I think) I know what's the problem. I want to access an array using a "for loop" but I can't because the values of the array are null. I don't know why and I don't know all the errors in this code, because I am still trying to run it. I can only compile, but as I said, I have the NPE problem when I run. However, for me it's logically acceptable the constructor receiving the parameter and the "for loop" in the way I wrote. So, when I run, the message is exactly this:
java.lang.NullPointerException at ArrayLab.initialize(ArrayLab.java:19) at Driver.main(Driver.java:16)
My questions are: What's wrong with my code? Why my array is null and it doesn't have the value assigned in the driver? How can I assign values to this array? Is there anything wrong with my constructor? And what about the "for loop"? What can I do to fix it?
public class ArrayLab
{
private int[] ArrayNum;
public ArrayLab(int Num)
{
int[] ArrayNum = new int[Num];
}
public void initialize()
{
for (int ANUM = 0; ANUM <= ArrayNum.length; ANUM++)
{
ArrayNum[ANUM] = (int) Math.round((Math.random() * 10));
}
}
public void print()
{
System.out.println(ArrayNum);
}
public void printStats()
{
double Sum = 0;
int Max = 0;
int Min = 0;
for (int ANUM = 0; ANUM < ArrayNum.length; ANUM++)
{
Sum = Sum + ArrayNum[ANUM];
if (ArrayNum[ANUM] > ArrayNum[Max])
{
Max = ANUM;
}
if (ArrayNum[ANUM] < ArrayNum[Min])
{
Min = ANUM;
}
}
double Average = Sum/ArrayNum.length;
System.out.println("Average Value: " + Average);
System.out.println("Maximum Value: " + Max);
System.out.println("Minimum Value: " + Min);
}
public void search(int GivenNumber)
{
for (int ANUM = 0; ANUM < ArrayNum.length; ANUM++)
{
if(GivenNumber == ArrayNum[ANUM])
{
System.out.println(GivenNumber + " was found.");
}
else
{
System.out.println(GivenNumber + " was not found.");
}
}
}
}
and
public class Driver
{
public static void main(String[] args)
{
//create new instance of the ArrayLab class with parameter of 10
ArrayLab array = new ArrayLab(10);
//print out the array created by ArrayLab constructor
array.print();
//initialize the array with random values
array.initialize();
//print the randomized array
array.print();
//print stats for the array
array.printStats();
//search for 3
array.search(3);
//search for 2
array.search(2);
}
}