(处理)当我尝试运行此代码时,我得到一个空指针异常

时间:2013-12-13 04:44:27

标签: java exception pointers null processing

程序在屏幕上随机创建10个正方形,然后10个点,然后它使用for循环来比较每个点与每个正方形以确定该点是否在正方形内,但每当我运行此代码时,行

    points[i].x > squares1[j].x && points[i].x < squares2[j].x && points[i].y > squares1[j].y && points[i].y < squares2[j].y

返回一个空指针异常,我无法解释为什么,任何人都可以帮忙。

主要代码

    PVector[] points;
    PVector[] squares1;
    PVector[] squares2;

    void setup()
    {
      size(800, 800);
      points = new PVector[10];
      squares1 = new PVector[10];
      squares2 = new PVector[10];
      for(int i = 0; i < 10; i+= 80)
      {
        squares1[i] = new PVector(random(0, width-80), i);
        squares2[i] = new PVector(squares1[i].x+80, squares1[i].y+80);
        rect(squares1[i].x, squares1[i].y, 80, 80);
      }
      for(int i = 0; i < points.length; i++)
      {
        points[i] = new PVector(random(width), random(height));
        for(int j = 0; j < 10; j++)
        {
          if(points[i].x > squares1[j].x && points[i].x < squares2[j].x && points[i].y > squares1[j].y && points[i].y < squares2[j].y)
          {
            fill(255, 0, 0);
            ellipse(points[i].x, points[i].y, 5, 5);
            println("Point " + i+1 + " is contained in figure " + j + ".");
          }
          else
          {
            fill(0);
            ellipse(points[i].x, points[i].y, 5, 5);
            println("Point " + i+1 + " is not contained in any figure.");
          }
        }
      }
    }

    void draw()
    {

    }

1 个答案:

答案 0 :(得分:2)

用i ++替换i + = 80;因此只初始化了第一个square1 [0]和square2 [0]。所以你得到一个空指针异常

相关问题