我正在做一个关于解析的类,这里是我的代码的一部分。嵌套类中的对象数组
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'的值是多少? – 2012-02-27 12:03:10
如果'v'不为空,那么在'setpackTotal'和'setpackType'调用之间'a'必须是不同的。添加'System.out.println'调用来查看值或通过代码进行调试。 – 2012-02-27 12:03:13
重新格式化你的代码之后 - 'i ++'语句应该在while块内部。但是这并不能解释NPE,在这里我们有一个无限循环。 – 2012-02-27 12:09:00