使用多个类中的方法时,java.lang.NullPointerException

时间:2018-10-29 00:23:12

标签: java object nullpointerexception null

我是Java编程的新手,我试图找出为什么我的代码总是给我错误java.lang.NullPointerException的原因。它应该得到6分,并创建2个三角形。

MAIN CLASS

public class Themain{
  public static void main (String[] args){
    Point pointone = new Point(1,2);
    Point pointtwo = new Point(3,4);
    Point pointthree = new Point(0,5);

    Point josh = new Point(1,2);
    Point abby = new Point(3,4);
    Point trevor = new Point(0,6);


    Triangle2D triangleone = new Triangle2D();
    Triangle2D triangletwo = new Triangle2D();

    triangleone.setPoint1(pointone);
    triangleone.setPoint2(pointtwo);
    triangleone.setPoint3(pointthree);

    triangletwo.setPoint1(josh);
    triangletwo.setPoint2(abby);
    triangletwo.setPoint3(trevor);    
  }
}

三角课

  public class Triangle2D{

  Point p1;
  Point p2;
  Point p3;

 //no args constructor
  public Triangle2D(){   
  }

  //set point one
   public void setPoint1(Point p){
    p1.setXPos(p.getXPos());
    p1.setYPos(p.getYPos());
  }
  //set point two
  public void setPoint2(Point p){
    p2.setXPos(p.getXPos());
    p2.setYPos(p.getYPos());
  }
 //set point three
  public void setPoint3(Point p){
    p3.setXPos(p.getXPos());
    p3.setYPos(p.getYPos());
  }

  //get point one
   public Point getPoint1(){
    return(p1);
  }

}

要点类

 public class Point{

  int x;
  int y;

   //args constructor
  public Point(int x, int y){
    this.x = x;
    this.y = y;
  }

  //get the x-coordiante
  public int getXPos(){
    return x;
  }

  //set the x-coordinate
  public void setXPos(int x){
    this.x = x;
  }


  //get the y-coordinate
  public int getYPos(){
    return y;
  }

  //set the y-coordinate
  public void setYPos(int y){
    this.y = y;
  }

  //is equals method

  public boolean isEquals(Point t){
    return(this.x == t.x && this.y == t.y);
  }

}

我不确定为什么会出现空错误。实际的代码比这要长得多,但是我已经选择了导致错误的部分,并将其放入此文件中。我主要是在写这篇文章,因为堆栈溢出表明代码太多。如果有人可以帮助我理解为什么会出现此错误,将不胜感激。

2 个答案:

答案 0 :(得分:0)

点p1;这是空

更改为这种代码模式

public void setPoint1(Point p){

    p1 = p;
}

或者您也可以在构造函数中构造点

public Triangle2D(){ 
    p1 = new Point (-1, -1);  // or even better create a zero arg constructor
}

答案 1 :(得分:0)

p1, p2, p3对象为空,您没有初始化它们。

2个解决方案:

  1. 初始化它们

    public Triangle2D(){   
        p1 = new Point();
        p2 = new Point();
        p3 = new Point();
    }
    

    需要为Point:0-arg constructor

  2. 添加public Point(){}
  3. 使用设置器时分配值

    public void setPoint1(Point p){
        p1 = p;
    }