Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

java - checking if a point is inside a specified Rectangle

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());
}

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");

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

AWT Rectangle already has contains method. ( link )

Task seems about if you understand how naming spaces conflict. For example, if you are lazy (it's one of most admired qualities of a programmer), then you can write:

public static class Rectangle {
    java.awt.Rectangle _r;

    public Rectangle(int x, int y) {
        this._r = new java.awt.Rectangle(x, y);
    }
    public boolean contains(Point p) {
        return this._r.contains(p);
    }
}

You generally do not want to reimplementing features nor extend classes.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...