检查一个点是否在指定的 Rectangle 内

2022-01-14 00:00:00 geometry java

好的,所以我正在为一个 Java 类进行分配,其中一部分是确定一个点是否在矩形的尺寸范围内.所以我创建了这段代码:

ok, so i'm doing an assignment for a Java class and one part of the assignment is to find out if a point is within the dimensions of a rectangle. so I created this code:

public boolean contains(Point p) {
    return (this.getLocation().getX() < p.getX() && this.getLocation().getY() < p.getY() &&
            this.getLocation().getX() + this.getWidth() > p.getX()  &&
            this.getLocation().getY() + this.getHeight() > p.getY());
}

我也创建了一个 Point 类,这就是我要求 Point p 参数的原因.为了测试这个 boolean 我在我的 Main 类中创建了一个简单的 if 语句:

I created a Point class as well, which is why I asked for a Point p parameter. To test this boolean I created a simple if statement in my Main class:

//check if one rectangle's point is inside another
if (rectangle.contains(rectangle2.getLocation()))
    System.out.println("the point is in the rectangle");

点的位置是(6,7).矩形 1 的点、宽和高分别为 (4,5)、9 和 3.我知道这一点在第一个矩形内,但是 println 语句没有显示,这意味着我创建的 boolean 肯定有问题,但我没有'没有看到错误,也许我的头是多云的,但有人可以向我指出这里有什么问题吗?

The location of the point is (6,7). The point, width, and height of rectangle 1 is (4,5), 9, and 3, respectively. I know for a fact that this point is inside the first rectangle, but the println statement is not showing, meaning there must be a problem with the boolean i created but I don't see an error, maybe my head is cloudy but can someone point out to me what's wrong here?

附:这都是控制台工作,我不是在处理一些 GUI 或图形编程.

P.S. this is all Console work, i'm not dealing with some GUI or graphics programming.

推荐答案

我觉得没问题.我会检查你的测试用例是否真的有你认为的数字;我还会检查您的访问器是否都返回了正确的值(我无法告诉您我将 getX() 实现为 {return this.y;} 的次数).除此之外,这是任何人的猜测.

It looks ok to me. I would check that your test case actually has the numbers you think it does; I would also check that your accessors are all returning the right values (I can't tell you the number of times I've implemented getX() as {return this.y;}). Other than that it's anyone's guess.

相关文章