问题描述
好吧,所以我有一个矩形应该基于以下方法创建:方法点,它将确定其中心的坐标以及高度和宽度的值,所有值均基于此测试
public void testRectangle1() {
Point center = new Point(20,30);
Rectangle rect = new Rectangle(center,20,20);
assertAll(
() -> assertEquals(10,rect.getTopLeft().getX()),() -> assertEquals(20,rect.getTopLeft().getY()),() -> assertEquals(30,rect.getBottomright().getX()),() -> assertEquals(40,rect.getBottomright().getY()),rect.getWidth()),rect.getHeight())
);
}
package net.thumbtack.school.figures.v1;
public class Point {
private int x,y;
public Point(int x,int y) {
this.x = x;
this.y = y;
}
public Point() {
this(0,0);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void moveto(int newX,int newY) {
x = newX;
y = newY;
}
public void moveRel(int dx,int dy) {
x += dx;
y += dy;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Point other = (Point) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
这是用于创建矩形的类
package net.thumbtack.school.figures.v1;
public class Rectangle {
public int width;
public int height;
public Point center;
public int xCenter;
public int yCenter;
private Point point;
public Rectangle(Point center,int width,int height) {
this.width=width;
this.height=height;
this.center=center;
}
public Point getTopLeft() {
Point point = getCenter();
point.moveRel(- width / 2,- height / 2);
return point;
}
public Point getBottomright() {
Point point = getCenter();
point.moveRel(width / 2,height / 2);
return point;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
public Point getCenter() {
Point center = new Point(xCenter,yCenter);
return center;
}
所以问题出在构造器public Rectangle(Point center,int height)
中,当我运行测试时它会返回错误的值
预期:,但仍是: 比较失败: 预期:10 实际:-10
预期:,但为: 比较失败: 预期:20 实际:-10
预期:,但仍是: 比较失败: 预期:30 实际:10
预期:,但仍是: 比较失败: 预期:40 实际:10
我不认为当我在其他但类似的压缩器中使用它们时,其他方法都会出现问题。
解决方法
如恶棍所述,您必须先使用xCenter
或yCenter
进行初始化,否则xCenter
和yCenter
的值为0。
修改getCenter()
方法:
public Point getCenter() {
Point point = new Point(center.getX(),center.getY());
return point;
}