2014-11-23 49 views
0

我創建了一個類,可以發現,它們之間的中點值的兩個點之間的距離:打印點的值到終端

public class Point { 

    private double x; 
    private double y; 

    public Point (double x, double y) { 

     this.x = x; 
     this.y = y; 
    } 

    public double getX() { 
     return x; 
    } 

    public void setX(double x) { 
     this.x = x; 
    } 

    public double getY() { 
     return y; 
    } 

    public void setY(double y) { 
     this.y = y; 
    } 

    public static void main (String[] args) { 
     Point p1 = new Point(1,1); 
     Point p2 = new Point(4,5); 
     System.out.println("The distance between p1 and p2 is: " + distance(p1, p2)); 
     System.out.println("The midpoint of p1 and p2 is: " + findMidpoint(p1, p2)); 
    } 

    public static double distance(Point p1, Point p2) { 
     return Math.sqrt((p1.getX() - p2.getX()) * (p1.getX() - p2.getX()) + 
          (p1.getY() - p2.getY()) * (p1.getY() - p2.getY())); 
    } 

    public static Point findMidpoint (Point p1, Point p2) { 
     return new Point((p1.getX() + p2.getX())/2, (p1.getY() + p2.getY())/2); 
    } 
} 

此代碼編譯罰款,但是當我運行它,它給出輸出:

The distance between p1 and p2 is: 5.0 
The midpoint of p1 and p2 is: [email protected] 

無論p1和p2的值如何,它都給出相同的中點值。我想輸出格式爲「(x,y)」的中點。

有人也可以解釋爲什麼我被迫使距離和findMidpoint方法是靜態的嗎?

+1

overide'toString()' – 2014-11-23 23:38:57

回答

3

爲什麼我一次比一次相同的輸出?

因爲您不是覆蓋toString方法。你看到的值是java的toString的實現。每個對象都有這種行爲。

將此方法放在您的point類中以覆蓋java的toString實現。

@Override 
public String toString(){ 
    return "("+x+", "+y+")"; 
} 

這會根據您的要求給出格式爲(x, y)的輸出。

爲什麼中點和距離是靜態的?

靜態方法是一個設計決定。它們可以被寫成非靜態的,但它會變得不那麼意義,因爲這些方法不會改變所涉及的任何點對象的狀態。

+0

'這會給你格式輸出(x,y)'......不是真的:P。你錯過了逗號。 – Tom 2014-11-23 23:50:04

+0

也缺少y和「之間的加號」)XD – Shiftz 2014-11-24 01:34:18

+0

我必須開始使用聯機語法檢查器。謝謝@Shiftz我糾正了。 – 2014-11-24 01:43:29

1

[email protected]Object#toString()的「默認」輸出行爲。如果你想改變這種狀況,則重寫此方法:

@Override 
public String toString() { 
    return "Point[" + 
     "x=" + x + 
     ", y=" + y + 
     "]"; 
} 

應打印:

Point[x=100.0, y=100.0] 

代替。

2

你需要創建一個toString()方法:

public String toString() { 
    return String.format("Point(%f,%f)",x,y); 
} 

然後你得到:

java Point 
The distance between p1 and p2 is: 5.0 
The midpoint of p1 and p2 is: Point(2.500000,3.000000)