ap计算机科学hw错误

时间:2014-12-07 02:58:09

标签: java arraylist nullpointerexception

我目前遇到以下代码错误。

import java.util.ArrayList;
public class Catapult
{
    ArrayList<Double> distance;

    Catapult()
    {
        ArrayList<Double> distance = new ArrayList<Double>();
    }

    public void calcDistance(Integer[][] data)
    {
        int counter = 0;

        for(int a = 0; a < data.length; a++)
        {
            double speed = data[a][0];
            for(int x = 0; x < data[0].length; x++)
              {
                double radian = Math.toRadians(data[0][1 + x]);
                double dist = (speed * speed * Math.sin(2 *radian)) / 9.8; 
                distance.add(dist);
              }
        }
    }

    public void print()
    {
        for(int x = 0; x < distance.size(); x++)
        {
            System.out.println(distance.get(x));
        }
    }
}
import java.util.ArrayList;
public class CatapultTester
{
   public static void main(String[] args)
   {
       Integer[][] data = {{20, 25, 30, 35, 40, 45, 50},
                           {25, 25, 30, 35, 40, 45, 50},
                           {30, 25, 30, 35, 40, 45, 50},
                           {35, 25, 30, 35, 40, 45, 50},
                           {40, 25, 30, 35, 40, 45, 50},
                           {45, 25, 30, 35, 40, 45, 50},
                           {50, 25, 30, 35, 40, 45, 50}};

       Catapult range = new Catapult();
       range.calcDistance(data);
       range.print();
    }
}

每当我尝试运行它时,我会得到java.lang.NullPointerException&#34; Null&#34;。这是一个分配,要求计算具有不同速度和角度的射弹的范围,这些射程存储在双阵列数据中。但是,错误会一直显示,并且不允许我将 dist 添加到数组列表距离

2 个答案:

答案 0 :(得分:5)

Catapult() {
    ArrayList<Double> distance = new ArrayList<Double>();
}

这将创建一个名为distance的新局部变量shadows您的实例变量distance

将该代码更改为:

Catapult() {
    distance = new ArrayList<Double>();
}

访问正确的distance变量。如果您尝试在代码中使用它,那么它将不再是null

是的,就像在建议的评论中一样,尝试学习如何使用调试器。这是自己找到这些错误的重要工具。

答案 1 :(得分:2)

Catapult()
{
    ArrayList<Double> distance = new ArrayList<Double>();
}

更改为

Catapult()
{
    distance = new ArrayList<Double>();
}