gpt4 book ai didi

java - 有人能弄清楚如何修复此代码吗?

转载 作者:行者123 更新时间:2023-12-02 04:50:56 24 4
gpt4 key购买 nike

这是我的代码..拜托我找不到它为什么不起作用..

(MyTriangle 类:)

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");
}
}

(MyPoint 类:)

   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)

最佳答案

您忘记初始化您的积分:

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);
}

关于java - 有人能弄清楚如何修复此代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29254433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com