【发布时间】:2020-08-25 07:15:17
【问题描述】:
矩形是在这个测试中使用的
@Test
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())
);
}
我已经有了课程,它应该可以正常工作,我主要是为了理解而添加它。
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;
}
}
所以我坚持矩形本身的第二类。首先,我很难形成将形成矩形本身的构造函数。还有关于矩形类中的填充方法,因为我很难理解它们应该返回什么,因为我在 Java 和编码方面经验不足。
public class Rectangle {
public int width = 0;
public int height = 0;
public Point center;
public Rectangle(Point center, int width, int height) {
int x = 0;
int y = 0;
width=x;
height=y;
}
public Point getTopLeft() {
Point point = new Point();
return point;
}
public Point getBottomRight() {
Point point = new Point();
return point;
}
public int getWidth() {
int x = 0;
return x;
}
public int getHeight() {
int y = 0;
return y;
}
}
【问题讨论】:
-
您显然需要将 x 和 y 值传递给您在
getTopLeft()和getBottomRight()中创建的点。由于您已经有了 center 点的坐标以及矩形的宽度和高度,因此这些角点的坐标应该很容易计算。你遇到了什么困难?顺便说一句,我敦促您阅读How to Ask,您是否还没有阅读。 -
就像
center一样,将topLeft和bottomRightPoint添加到您的Rectangle。然后,您可以在构造函数中根据center、width和height计算这些Points。然后在您的get和set方法中返回这些“变量”(即字段)。先在纸上做,然后它就会变得明显。 -
至于您的构造函数:看起来不错。但是,在
getWidth()和getHeight()中,您需要返回width和height而不是 0(这就是您正在执行的操作)。由于这似乎是某种练习,我建议您与您的老师联系或获取有关 Java 和编程基础知识的教程,因为如果您已经在为这项任务苦苦挣扎,您需要投入更多的工作来获得基础知识否则你以后会后悔的。 - 顺便说一句,你提供了Point类还是你从其他人那里得到的? -
点是锻炼的一部分
标签: java constructor rectangles