为什么我要用这个代码得到一个NullPointerException呢?
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++;
}
}在while循环的第一行,我得到了它的第一次遍历错误。我还有一个单独的课程:
public class Job {
public int start, end, weight;
}以及文本文件:
0 3 3
1 4 2
0 5 4
3 6 1
4 7 2
3 9 5
5 10 2
8 10 1谢谢。
发布于 2013-10-29 14:09:14
NullPointerException
在需要对象的情况下,应用程序尝试使用null时引发。其中包括:
到目前为止,数组中的所有值都是null。因为您没有在其中插入任何作业对象。
job[i].start = input.nextInt(); // job[i] is null.您所要做的就是初始化一个新的Job对象并将其分配给当前的index。
变成,
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-29 14:11:59
请参阅4.12.5. Initial Values of Variables
对于所有引用类型(§4.3),默认值为null。
您需要在尝试访问job数组之前初始化它,现在它就像编写null.start,这当然会导致NullPointerException。
发布于 2013-10-29 14:09:23
您刚刚初始化了一个Job类型的数组,没有初始化数组中的每个元素,因此出现了异常。
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++;
}https://stackoverflow.com/questions/19660555
复制相似问题