java - 创建 setX(x) 时遇到问题

标签 java methods

我写了以下内容:

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) 、 setY (y) 方法而不创建新对象时遇到问题... 有人可以帮我编写 setX() 方法吗?

谢谢!

最佳答案

你可以这样做:

{
        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) );
} 

然后: void setX(int x)

{
      setValues(x,getY());
}

关于java - 创建 setX(x) 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5765351/

相关文章:

java - Java 中非实例化类的内存管理是如何工作的?

java - 替换二维数组中特定位置的字符?

python - 传递列表并将其长度设置为python中的默认参数

java - containsAny 检查的最快方法是什么?

java - 按下按钮后应用程序崩溃 - 蓝牙 arduino

java - 在 main 中调用带有引用变量的方法

http - 有什么方法可以检查 POST url 是否存在?

ruby - Ruby 方法应该返回 nil 还是空对象

java - 如何在 Jgit 中 rebase

java - 查询日期范围内的记录时需要向后拉记录