2016-01-20 80 views
-1

我正在研究編程原理II的實驗,並且我有一個課程提供了一個點,包括設置點的方法和計算其他點之間的距離。計算距離在用類運行器測試時運行良好,但是當我使用其他類作爲對象時,我得到了距離公式的錯誤。Java數學錯誤

import java.lang.Math; 

public class MyPoint { 
private double x; 
private double y; 

public MyPoint(double dubx, double duby) 
{ 
    x=dubx; 
    y=duby; 
} 

public void setX(double dub) { 
    x = dub; 
} 

public void setY(double dub) { 
    y = dub; 
} 

public double getX() { 
    return x; 
} 

public double getY() 
{ 
    return y; 
} 
public double distance (MyPoint otherPoint) 
{ 
    return Math.sqrt(Math.pow((otherPoint.getX()-getX()),2)+(Math.pow((otherPoint.getY()-getY()),2))); 
} 
public MyPoint midpoint(MyPoint otherPoint) 
{ 
    MyPoint point = new MyPoint((otherPoint.getX()+getX()/2),(otherPoint.getY()+getY())/2); 
    return point; 
} 
} 

這是我遇到錯誤的類。距離部分得到空指針異常。

下面是我通過什麼:

import java.lang.Math; 

public class MyTriangle 
{ 
private MyPoint v1; 
private MyPoint v2; 
private MyPoint v3; 

public MyPoint getPoint1() 
{ 
    return v1; 
} 
public MyPoint getPoint2() 
{ 
    return v2; 
} 
public MyPoint getPoint3() 
{ 
    return v3; 
} 
public void setPoint1(double x, double y) 
{ 
    v1= new MyPoint(x,y); 
} 
public void setPoint2(double x, double y) 
{ 
    v2 = new MyPoint(x,y); 
} 
public void setPoint3(double x, double y) 
{ 
    v2= new MyPoint(x,y); 
} 
public double getArea() 
{ 
    double a= v2.distance(v3); 
    double b= v1.distance(v3); 
    double c= v1.distance(v2); 
    double s= (a+b+c)/2; 
    return Math.sqrt(s*(s-a)*(s-b)*(s-c)); 
} 
} 

public class TestMyTriangle 
{ 
public static void main(String [] args) 
{ 
    MyTriangle tr1 = new MyTriangle(); 
    tr1.setPoint1(17,17); 
    tr1.setPoint2(5,30); 
    tr1.setPoint3(5,17); 
    System.out.println("Area:\t"+tr1.getArea()); 
    } 
} 

和錯誤:

Exception in thread "main" java.lang.NullPointerException 
at MyPoint.distance(MyPoint.java:34) 
at MyTriangle.getArea(MyTriangle.java:37) 
at TestMyTriangle.main(TestMyTriangle.java:9) 

我似乎無法推測出來。請幫忙。

+3

'公共無效setPoint3(雙X,雙Y) { V2 =新MyPoint(X,Y); } ' –

+0

使用調試器查看哪個對象沒有被初始化。 –

回答

-1

你得到空指針,因爲V3爲空:

修復有:

public void setPoint3(double x, double y) 
{ 
    v3= new MyPoint(x,y); // instead of v2 
} 

另一個TIPP:計算方不使用Math.pow(x,2)。 儘管它工作。 該代碼是清潔器和更快如果使用

x*x instead Math.pow(x,2); 
+0

你找到了我。儘管如此,仍然有錯誤。該地區應該是30,但我得到了78. –

+0

試着接受我的答案,因爲它現在被關閉,你不能得到另一個答案。 – AlexWien

+1

爲什麼你首先回答重複的問題? – redFIVE