如何仅获取Point类中的x和y

时间:2018-11-07 00:22:03

标签: java

我有一个变量私有Point _centralStation,位于我称为她的城市的班级中。 主类中的用户决定哪个值将成为CentralStation的位置。 所以他举了一个例子: 点中心=新Point(5,5)。 我想创建一个调用MoveCentralStation(int x,int y)的方法 将位置从他的最后一个值移到新值,但是 新点必须位于x,y轴的第一季度。 我的意思是例如x不能为-4。 举例来说,是5,5 现在用户输入-4,5 如何分别处理x和y新值? 谢谢

1 个答案:

答案 0 :(得分:0)

您必须更好地解释自己。但是,这是我的理解。 你有这样的课程:

class City{

private Point _centralStation;

public City(){
    this._centralStation = new Point(5,5);
    //the initialization you specified
}

public void moveCentralStation(int new_x, int new_y){
    //TODO exactly what you have to implement
}

public Point getCentralStation(){
    //since you are not implementing just getters and setters you rather do
    return new Point(_centralStation.x,_centralStation.y);
    //instead of return _centralStation [this is what we call defensive copies]
}
}

好吧,在代码中的某个地方,客户会打电话

City c = new City();
c.moveCentralStation(x,y); //given x,y are variables in the client's context

这些是moveCentralStation(int x,int y)操作的要求:

  1. x坐标为正
  2. y坐标为正

首先,我建议您在编码方式上遵循样式约定:仅对类名使用大写字母。让我们跳入真正的问题。 我们需要完善上述要求,以使其符合特定的实现。他们还不够清楚。我可能建议的一个优化示例如下:

  1. 如果x坐标小于零,则将引发IllegalArgumentException
  2. 如果y坐标小于零,则将抛出IllegalArgumentException

这很容易实现:

public void moveCentralStation(int new_x, int new_y){
    if(new_x < 0) throw new IllegalArgumentException("x must be positive");
    if(new_y < 0) throw new IllegalArgumentException("y must be positive");
   _centralStation.x = new_x;
   _centralStation.y = new_y;
}

仅在私有字段都是一致的情况下设置私有字段是一种好习惯。