3

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.

4

3 回答 3

8

NullPointerException

Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • 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++;
    }
于 2013-10-29T14:09:14.777 回答
5

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.

于 2013-10-29T14:11:59.240 回答
4

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++;
    }
于 2013-10-29T14:09:23.123 回答