I have a piece of code that is ment to scan in a large array of numbers (as integers) and store them into a scenario object. However after I get to the 3499th object (it prints the 3498th J) it crashes with a null pointer. I looked for a maximum array size but couldn't find anything on the internet except 2^32-5 however I'm not even close to that limit.
in1scan = new Scanner(in1);
in2scan = new Scanner(in2);
scenario[] ret= new scenario[9999];
int j=0;
while (in1scan.hasNext()){
String[] input=(in1scan.next().split(",", 16));
ret[j]=new scenario();
for (int i=0; i<16;i++){
ret[j].input[i]=Integer.parseInt((input[i]));
}
j++;
}
j=0;
while (in2scan.hasNext()){
ret[j].correct=Integer.parseInt(in2scan.next()); //here things go wrong
j++;
System.out.println(j);
}
Does anybody know what is wrong? And yes I know that I can use nextInt instead of the current roundabout way of accepting numbers but I'm going to add some extra functionality that requires it to be handled this way.
You have "run out" of ret.
In this part of the code you create the first in1scan.size() elements of ret
while (in1scan.hasNext()){
String[] input=(in1scan.next().split(",", 16));
for (int i=0; i<16;i++){
ret[j]=new scenario();
ret[j].input[i]=Integer.parseInt((input[i]));
}
j++;
}
Here you use the first in2scan.size() element of ret. If in2scan.size() > in1scan.size() then ret[j] will be null and so .correct cannot be called upon it
j=0;
while (in2scan.hasNext()){
ret[j].correct=Integer.parseInt(in2scan.next()); //here things go wrong
j++;
System.out.println(j);
}
Stepping through in a debugger will (hopefully) confirm this
The stack trace tells you the exception is thrown at
ret[j].correct=Integer.parseInt(in2scan.next()); //here things go wrong
so either ret, ret[j] or in2scan is null.
To find out which it is, set an exception breakpoint for NullPointerException, and run the program in debug mode. That will suspend execution at the time the exception is thrown, allowing you to inspect program state at that time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With