2011-04-23 78 views
0

我寫了下面:有問題創造setX的(X)

public class Point 
{ 
    private double _radius , _alpha;  

    public Point (int x , int y) 
    { 
     //if one or more of the point values is <0 , the constructor will state a zero value. 
     if (x < 0) 
     { 
      x = 0; 
     } 

     if (y < 0) 
     { 
      y = 0; 
     } 
     _radius = Math.sqrt (Math.pow(x,2) + Math.pow (y,2)) ; 
     _alpha = Math.toDegrees(Math.atan ((double)y/x)); 
    } 

    public Point (Point other) // copy constructor 
    { 
     this._radius = other._radius ; 
     this._alpha = other._alpha ; 
    } 

    int getX() 
    { 
     return (int) Math.round (Math.sin(_alpha)*_radius); 
    } 

    int getY() 
    { 
     return (int) Math.round (Math.cos(_alpha)*_radius); 
    } 

    void setX (int x) 
    { 

    } 

} 

我只是有問題寫下setX的(X),塞蒂(y)的方法,而無需創建一個新的對象...... 有人能幫我寫setX()方法嗎?

謝謝!

回答

1

可以做到這一點:

{ 
     int y = getY(); 
     _radius = Math.sqrt (Math.pow(x,2) + Math.pow (y,2)) ; 
     _alpha = Math.toDegrees(Math.atan ((double)y/x)); 
} 

,或者如上面暗示的,定義該方法:

void setValues (int x, int y) 
{ 
      _radius = Math.sqrt (Math.pow(x,2) + Math.pow (y,2)) ; 
      _alpha = Math.toDegrees(Math.atan ((double)y/x)); 
} 

然後: 空隙setX的(INT X)

{ 
     setValues(x,getY()); 
} 
+0

如果我不想定義另一種方法? – 2011-04-23 17:16:15

+0

然後使用第一個代碼(在「或,as ...」之前)。 – ronash 2011-04-23 17:17:20

+0

但是,如果我不能將功能添加到除_radius之外的我的課程,_alpha我會做什麼外殼? – 2011-04-23 17:24:02

0

爲什麼不記錄xy,並且只在需要時才計算半徑和alpha值。

這樣,你有

public void setX(double x) { _x = x; } 
public double getX() { return _x; } 

編輯:你可以做到這一點。

public Point(double x, double y) { 
    setRadiusAlpha(x, y); 
} 

private void setRadiusAlpha(double x, double y) { 
    if(x < 0) x = 0; 
    if(y < 0) y = 0; 
    _radius = Math.sqrt(x*x + y*y) ; 
    _alpha = Math.toDegrees(Math.atan(y/x)); 
} 

public void setX() { setRadiusAlpha(x, getY()); } 
public void setY() { setRadiusAlpha(getX(), y)); } 
+0

由於我只能使用_alpha和_radius進行計算... – 2011-04-23 16:28:31

+0

@Master C,如果這是家庭作業,您應該標記它如此。 – 2011-04-23 16:43:18

+0

標記了它......但我如何使用_radius和_alpha特徵創建設置方法? – 2011-04-23 16:48:15

0

當X或Y的變化,就需要重新計算基於所更改的新價值和有沒有舊的半徑和α。最簡單的方法是將_radius和_alpha設置爲它自己的私有函數(也許稱爲setXY),並從構造函數以及從setX和setY中調用該函數。

+0

你能解釋一下嗎?因爲我沒有理解它...... – 2011-04-23 17:05:17