【发布时间】:2012-02-27 11:59:29
【问题描述】:
我即将开一个关于解析的课程,这是我的部分代码。
public class Parsing {
//some other atributes here
public class Pack {
String type;
int[] brand;
int total;
}
Pack[] v = new Pack[25];
public void setpackType(int a, String b) {
v[a].type = b;
}
public String getpackType(int a) {
return v[a].type;
}
public int getpackTotal(int a) {
return v[a].total;
}
public void setpackTotal(int a, int b) {
v[a].total = b;
}
public void setpackBrand(int a, int b, int c) {
v[a].brand[b] = c;
}
和
public final void process(String s) throws FileNotFoundException {
Scanner scanner;
scanner = new Scanner(new File(s));
try {
if (scanner.hasNext()) {
int y = scanner.nextInt();
int i = 1;
while (i <= y) {
v[i] = new Pack();
setpackType(i, scanner.next());
setpackTotal(i, scanner.nextInt();
int k = 0;
while (k < hh) {
setpackBrand(i, k, scanner.nextInt());
k++;
}
i++;
}
}
} finally{
scanner.close();
}
}
}
它编译没有错误,但是当我尝试运行时,我得到了这个:
Exception in thread "main" java.lang.NullPointerException
at Parsing.setpackTotal(Parsing.java:112)
at Parsing.process(Parsing.java:153)
at Parsing.main(Parsing.java:202)
我已经逐行测试了。 setpackType 工作得很好!
但我不明白为什么 setpackTotal 和 setpackBrand 不能工作。
非常感谢您的帮助:)
【问题讨论】:
-
如果
i超过 24(v中的最后一个索引),您将收到此异常。process()中y的值是多少? -
如果
v不为空,则a在setpackTotal和setpackType调用之间必须不同。添加System.out.println调用以查看值,或通过代码进行调试。 -
重新格式化代码后 -
i++语句应该在 while 块内。但这并不能解释 NPE,这里我们有一个无限循环。 -
顺便说一句-正如您显示的代码无法编译的那样,很难判断问题是在此草稿/片段中还是在我们尚未看到的真实代码中。 ..
-
y 是 4。 i++ 实际上在 while 块内。整个代码很长,我不能把它放在这里,我想:/但它已经编译了。
标签: java arrays nullpointerexception nested