【发布时间】:2020-09-21 05:15:37
【问题描述】:
好的,所以我有一个应该基于以下创建的矩形:将创建它的中心坐标的方法点以及高度和宽度的值,所有值都基于此测试
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()),
() -> assertEquals(20, rect.getWidth()),
() -> assertEquals(20, 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 width, int height) 中,当我运行测试时,它会返回接线值
预期: 但结果: 比较失败: 预计:10 实际:-10
预期: 但实际为: 比较失败: 预计:20 实际:-10
预期:,但结果: 比较失败: 预计:30 实际:10
预期: 但实际为: 比较失败: 预计:40 实际:10
我不认为问题出在其他方法上,因为当我在不同但相似的收缩器中使用它们时,一切正常。
【问题讨论】:
-
在您调用
getCenter()的Rectangle方法中,它通过xCenter和yCenter。据我所知,这些从未正确初始化。所以这可能就是你得到错误结果的原因。 -
有点离题了,但是当您将矩形的中心放在位置 3,3 或说位置 11,11 时会发生什么,getTopLeft 和 getBottomRight 的答案仍然正确吗?这可能取决于您的要求,但如果我是您,我会添加奇值坐标和大小的测试。此外,鉴于您的点类有一个 equals 方法,您可以断言点而不是点的组件
标签: java constructor rectangles