So, right after the public class declaration, I’ve declared an array as follows:
public String[] accept;
From here then, I’m looking to take user input to see how long this array should be – and following this, we’d enter into a loop to populate the array with Strings. I put the following into a method;
if (scanner.hasNextInt()) {
wcount = scanner.nextInt();
//create the array.
String accept[] = new String[wcount];
}
System.out.println(accept.length);
But unfortunately, no nice. Java returns with;
Exception in thread "main" java.lang.NullPointerException
Obviously, attempting to go straight into a for loop to populate the array, will also give the same results. At first glance, I’m assuming this has something to do with it being initialised as a public array outside of the method itself – but I’m honestly not too sure. Can anyone lend a hand on this?
You are declaring a new array in your if block, which is hiding your previously declared array. When the block exits, the variable goes out of scope and you get an NPE attempting to access the (unchanged) instance variable. Change your code to actually initialize your instance variable like so: