Java:尝试从ArrayList获取数字到数组时的空指针访问

时间:2017-03-28 16:13:35

标签: java nullpointerexception null

我需要帮助将数字从ArrayList(listInt)移动到三个不同的数组(iN,v和w)。

`import java.io. ; import java.util。;

公共课ReadingFileThree {

public static void main(String[] args) throws FileNotFoundException{

    //Try Catch for error catching
    try{

        int n = 0,C;  //Number of items and maximum capacity
        int iN[] = null,v[] = null,w[] = null;  //Item number, weights and values of items
        int V[][];  //Table to store results of sub-problems

        //Calling inbuilt methods to open the file we wish to read
        Scanner s = new Scanner(new File("easy.20.txt"));

        //An ArrayList is used because it increases in size dynamically
        ArrayList<Integer> listInt = new ArrayList<Integer>(); //Int ArrayList

        //Method for adding the numbers in the file to the Int ArrayList
        while (s.hasNextLine()){
            listInt.add(s.nextInt());
            n++;
        }

        //Closing the file. Need to be done or we get errors and memory leaks
        s.close();

        //Hold the maximum capacity of the knapsack (The last int in the file)
        C = listInt.get(n-1);




        for(int i = 0; i < n; i++){
            iN[i] = listInt.get(i+1);   //item number
            v[i] = listInt.get(i+2);  //weight of item
            w[i] = listInt.get(i+3);  //value of item
            i = i+2;
        }

        //Untested next stage
        //V = new int[n+1][C+1];  //initialising the table to hold results
        //for(int i = 0; i <= C; i++) V[0][i] = 0;
        //}

        //Print out commands for testing purposes
        System.out.println("All the numbers in the ArrayList are: " + listInt);
        System.out.println("n = " + n);
        System.out.println("C = " + C);


    }
    catch(Exception e) {
        System.out.println("File not found yo");
    }

}

} `

问题出现在for循环中。尝试在那里使用数组时出现错误。错误是:空指针访问问题

正在读取的文件如下所示。

4 1 16 34 2 3 30 3 46 34 4 42 47 10

  • 第一行的数字是项目数
  • 最后一行的数字是背包的容量
  • 中间的四行显示:项目编号 - 值 - 重量

我没有太多使用Java,请帮助。

2 个答案:

答案 0 :(得分:0)

很简单,问题是您在尝试为iN,v和w分配值时正在访问空对象。至少应该在为数组赋值之前在某个时刻初始化数组。

由于你已经在使用ArrayList,它似乎是你的赋值所允许的,所以为什么不将这些数组变量声明为该对象类型并插入到该对象而不是创建静态数组?

最后,更多的是风格,我通常喜欢在我的代码中使用更多描述性的变量名称,这样可以减少对它们的含义的混淆。例如,我的猜测是v代表值,w代表上面示例中的权重,但for循环中的注释表明该假设是错误的。

答案 1 :(得分:0)

我认为for循环不正确。我认为它应该像下面这样(我已经测试过这段代码)

for(int i = 0; i < n; ){
    iN[i] = listInt.get(i+0); //item number 
    v[i] = listInt.get(i+1); //weight of item 
    w[i] = listInt.get(i+2); //value of item
    i = i+3; 
}
相关问题