2012-02-27 141 views
1

我正在做一个关于解析的类,这里是我的代码的一部分。嵌套类中的对象数组

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工作得很好!

但我不明白为什么setpackTotalsetpackBrand无法正常工作。

非常感谢你的帮助:)

+0

如果'i'超过24('v'中的最后一个索引),你会得到这个异常。 'process()'中'y'的值是多少? – 2012-02-27 12:03:10

+0

如果'v'不为空,那么在'setpackTotal'和'setpackType'调用之间'a'必须是不同的。添加'System.out.println'调用来查看值或通过代码进行调试。 – 2012-02-27 12:03:13

+0

重新格式化你的代码之后 - 'i ++'语句应该在while块内部。但是这并不能解释NPE,在这里我们有一个无限循环。 – 2012-02-27 12:09:00

回答

2

数组在Java是零索引,请尝试更改i变量在process方法从0开始代替:

int i = 0; 
while (...) { 
    ... 
    i++; 
} 
+0

我改变了它,但没有任何不同。但是,谢谢你的尝试。 – username10 2012-02-27 13:02:27

0

您需要更改setpackTotal()到:

public void setpackTotal(int a, int b) { 
    v[a] = new Pack(); 
    v[a].total=b; 
} 
+0

谢谢。但它返回'0',而不是实际值:( – username10 2012-02-27 12:50:31

+0

他**是**这样做:'v [i] = new Pack();'它将覆盖当前实例! – falsarella 2012-02-27 14:13:31

0

忽略缺少)这里:

setpackTotal(i, scanner.nextInt(); 

NullPointerException可能是由于scanner.nextInt()引起的。

尝试调试scanner来解决问题。

另外,Peter's answer解决了部分问题。