Having problem creating setX(x)
I wrote the following:
开发者_如何学运维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)
{
}
}
I'm just having problems write down the setX(x) , setY (y) methods without creating a new object... Can some one help me write the setX() method ?
Thanks !
You can do this:
{
int y = getY();
_radius = Math.sqrt ( Math.pow(x,2) + Math.pow (y,2) ) ;
_alpha = Math.toDegrees( Math.atan ((double)y/x) );
}
or, as implied above, define the method:
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) );
}
And then: void setX (int x)
{
setValues(x,getY());
}
Whenever x or y changes, you need to recalculate the radius and alpha based on the new value that's changed and the old one that hasn't. The easiest way to do that is to move the calculation that sets _radius and _alpha into its own private function (call it setXY perhaps), and call that function from the constructor as well as from setX and setY.
Why don't you record x
and y
and calculate radius and alpha only when you need it.
That way you have
public void setX(double x) { _x = x; }
public double getX() { return _x; }
EDIT: You can do this.
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)); }
精彩评论