开发者

Probably a casting problem - Java

I wrote the following code:

public class Point2
{
    private double _radius , _alpha;    

    public Point2 ( 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 Point2 (Point2 other) // copy constructor
    {
        this._radius = other._radius ;
        this._alpha = other._alpha ;
    }

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

    public int getY()
    {
        return (int) 开发者_运维技巧Math.round ( Math.cos(_alpha)*_radius );   
    }

    public void setX (int x)
    {
        if (x >=0 )
        {
            _radius = Math.sqrt ( Math.pow (x,2) + Math.pow(getY(),2) );
            _alpha = Math.toDegree ( Math.atan ((double)getY()/x));
        } 
    }
}

The problem is that the compiler gives me an error on: _alpha = Math.toDegrees( Math.atan ((double)y/x) ); it says: "*cannot find symbol - method toDegree(double); maybe you meant: toDegrees(double)* "

What seems to be the problem ?

Thanks !


READ YOUR CODE!

    _radius = Math.sqrt ( Math.pow (x,2) + Math.pow(getY(),2) );
    _alpha = Math.toDegree ( Math.atan ((double)getY()/x));

That line says Math.toDegree instead of toDegrees!


because you wanted to use toDegrees()


I'd question the wisdom of setting negative x and y input values equal to zero. Talk about a nasty surprise for clients! Negative values make sense in most contexts. The fact that you have radius and theta as member variables suggest that these are points in the complex plane. Negative x and y values certainly do make sense.

I also agree with the recommendation to lose those awful underscores in your variable names. They're not necessary in this day and age, when IDEs can highlight member variables easily enough. You can prefix those with this. if you wish. Underscores are just an ugly artifact from C++ and emacs.


Probably unrelated, but your code is going to blow chunks if x is less than or equals zero. You can't divide by zero.

Also, am I the only one that sees that his code already uses the plural? Seems the compiler is confused.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜