use*_*639 3 java nullpointerexception
为什么我用这段代码得到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++;
}
}
Run Code Online (Sandbox Code Playgroud)
我在第一次运行时在while循环的第一行得到了错误.我还有一个单独的课程:
public class Job {
public int start, end, weight;
}
Run Code Online (Sandbox Code Playgroud)
和文本文件:
0 3 3
1 4 2
0 5 4
3 6 1
4 7 2
3 9 5
5 10 2
8 10 1
Run Code Online (Sandbox Code Playgroud)
谢谢.
当应用程序在需要对象的情况下尝试使用null时抛出.这些包括:
抛出null就好像它是一个Throwable值.
Job [] job = new Job [100];
截至目前,数组中的所有值都是null.因为您没有在里面插入任何Job对象.
job[i].start = input.nextInt(); // job[i] is null.
Run Code Online (Sandbox Code Playgroud)
你要做的就是初始化一个新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++;
}
Run Code Online (Sandbox Code Playgroud)