Reputation: 81
Why am I getting a NullPointerException with this code?
public static void main(String args[]) throws FileNotFoundException {
int i = 0;
Job[] job = new Job[100];
File f = new File("Jobs.txt");
Scanner input = new Scanner(f);
while (input.hasNextInt()) {
job[i].start = input.nextInt();
job[i].end = input.nextInt();
job[i].weight = input.nextInt();
i++;
}
}
I get the error at the very first line of the while loop on its very first run-through. I also have a separate class:
public class Job {
public int start, end, weight;
}
and the text file:
0 3 3
1 4 2
0 5 4
3 6 1
4 7 2
3 9 5
5 10 2
8 10 1
Thank you.
Upvotes: 3
Views: 200
Reputation: 121998
Thrown when an application attempts to use null in a case where an object is required. These include:
Throwing null as if it were a Throwable value.
Job[] job = new Job[100];
As of now all values in array are null
. Because you not inserted any Job objects inside.
job[i].start = input.nextInt(); // job[i] is null.
What you have to do is just initialize a new Job
object and assign to the current index
.
Becomes,
while (input.hasNextInt()) {
Job job = new Job();
job.start = input.nextInt();
job.end = input.nextInt();
job.weight = input.nextInt();
job[i] =job;
i++;
}
Upvotes: 8
Reputation: 95948
See 4.12.5. Initial Values of Variables:
For all reference types (§4.3), the default value is null.
You need to initialize job
array before trying to access it, now it's like writing null.start
, which of course causes NullPointerException
.
Upvotes: 5
Reputation: 223187
You just initialized an array of Job
type, you haven't initialized each element in the array, hence the exception.
while (input.hasNextInt()) {
job[i] = new Job(); // initialize here
job[i].start = input.nextInt();
job[i].end = input.nextInt();
job[i].weight = input.nextInt();
i++;
}
Upvotes: 4