public class MyTriangle {
private MyPoint v1;
private MyPoint v2;
private MyPoint v3;
public MyTriangle(int x1,int y1,int x2,int y2,int x3,int y3){
v1.setPointXY(x1, y1);
v1.setPointXY(x2, y2);
v1.setPointXY(x3, y3);
}
public MyTriangle(MyPoint v1,MyPoint v2,MyPoint v3){
this.v1.setPointXY(v1.getPointX(), v1.getPointY());
this.v2.setPointXY(v2.getPointX(), v2.getPointY());
this.v3.setPointXY(v3.getPointX(), v3.getPointY());
}
public String toString(){ return "Triangle @ " + v1.toString()+ ", " + v2.toString() + ", " + v3.toString() ;
}
public double getPerimeter(){return v1.distance(v2) + v2.distance(v3)+ v3.distance(v1);
}
public void printType(){
if(v1.distance(v2) == v2.distance(v3) && v2.distance(v3) == v3.distance(v1))
System.out.println("equilateral\n");
else if(v1.distance(v2) == v2.distance(v3) || v2.distance(v3) == v3.distance(v1) || v1.distance(v2)==v3.distance(v1))
System.out.println("isosceles\n");
else System.out.println("scalene\n");
}
}
class MyPoint{
private int x;
private int y;
public MyPoint(int x,int y){
this.x=x;
this.y=y;
}
public void setPointXY(int x,int y){
this.x=x;
this.y=y;
}
public void setPointX(int x){
this.x=x;
}
public void setPointY(int y){
this.y=y;}
public int getPointX(){return x;}
public int getPointY(){return y;}
public double distance(int x,int y){
return Math.sqrt(Math.pow(this.x - x,2.0) + Math.pow(this.y - y ,2.0) );
}
public double distance(MyPoint p){
return Math.sqrt(Math.pow(this.x - p.x,2.0) + Math.pow(this.y - p.y ,2.0) );
}
public String toString(){
return "("+x+","+y+")";}
}
public class TestMyTriangle {
public static void main(String[] args){
MyTriangle t1=new MyTriangle(2,3,4,1,3,5);
MyPoint p1=new MyPoint(2,2);
MyPoint p2=new MyPoint(3,3);
MyPoint p3=new MyPoint(1,1);
MyTriangle t2= new MyTriangle(p1,p2,p3);
System.out.print(t1.toString() + " With perimeters " + t1.getPerimeter() + " of type: ");
t1.printType();
System.out.print(t2.toString() + " With perimeters " + t2.getPerimeter() + " of type: ");
t2.printType();
}
}
错误:
Exception in thread "main" java.lang.NullPointerException at MyTriangle.<init>(MyTriangle.java:7)
at TestMyTriangle.main(TestMyTriangle.java:3)
答案 0 :(得分:2)
您忘了初始化积分:
public MyTriangle(int x1,int y1,int x2,int y2,int x3,int y3){
v1 = new MyPoint();
v2 = new MyPoint();
v3 = new MyPoint();
v1.setPointXY(x1, y1); // without initializing v1, this line causes a
// NullPointerException
v2.setPointXY(x2, y2);
v3.setPointXY(x3, y3);
}
甚至更好:
public MyTriangle(int x1,int y1,int x2,int y2,int x3,int y3){
v1 = new MyPoint(x1,y1);
v2 = new MyPoint(x2,y2);
v3 = new MyPoint(x3,y3);
}
答案 1 :(得分:0)
您尚未初始化对象
MyPoint v1;
MyPoint v2;
MyPoint v3;