public class Test {
public int [] x;
public Test(int N)
{
int[] x = new int [N];
for (int i=0;i<x.length;i++)
{
x[i]=i;
StdOut.println(x[i]);
}
}
public static void main(String[] args) {
String path = "/Users/alekscooper/Desktop/test.txt";
In reader = new In(path);
int size=reader.readInt();
StdOut.println("Size = "+size);
Test N = new Test(size);
StdOut.println(N.x[3]);
}
/* ADD YOUR CODE HERE */
}
Hello guys. I'm learning Java through reading Robert Sedgwick's book on algorithms and I'm using his libraries such as StdOut, for example. But the question is about Java in general. I don't understand why Java here throws a NullPointerException. I do know what that means in general, but I don't know why it is here because here's what I think I'm doing:
read an integer number from the file - the size of the array in the class Test. In my test example size=10, so no out-of-bound type of thing happens.
print it.
create the object N of type Test. In this object I think I create an array of size that I have just read from the file. For fun I initialize it from 0 to size-1 and print it. So far so good.
and here where it all begins. Since my class is public and I've run the constructor I think I have the object N which as an attribute has the array x with size elements. However, when I'm trying to address x, for example,
StdOut.println(N.x[3]);
Java throws NullPointerException.
Why so? Please help and thank you very much for your time.