I created a point class in Java:
public class Point { private final float THRESHOLD = (float) 0.0001; private final float x; private final float y; //getter public float getX(){return x;} public float getY(){return y;} //constructor public Point(float x,float y){this.x = x;this.y = y;} //equals public boolean equals(Object p1) { if (p1 != null && p1.getClass() == getClass()) {return (Float.floatToIntBits(x) == Float.floatToIntBits(((Point) p1).x)) ||(Float.floatToIntBits(y) == Float.floatToIntBits(((Point) p1).y) ||Math.abs(x - ((Point) p1).x) < THRESHOLD && Math.abs(y - ((Point) p1).y) < THRESHOLD);} return false; } //toString public String toString() { return "x=" + x + " y=" + y; } }
Then I created a rectangle class using the two points as topLeft and bottomright:
public final class Rectangle { private final Point topLeft; private final Point bottomRight; //getters public Point gettopLeft() {return topLeft;} public Point getbottomRight() {return bottomRight;} //constructor Rectangle(Point topLeft,Point bottomRight){this.topLeft = topLeft; this.bottomRight = bottomRight;} Rectangle(float topLeftX,float topLeftY,float bottomRightX, float bottomRightY){ this(new Point(topLeftX,topLeftY),new Point(bottomRightX,bottomRightY)); } //equals public boolean equals(Object r1) { if (((Rectangle)r1).bottomRight == this.bottomRight && ((Rectangle)r1).topLeft == this.topLeft && r1.getClass() == getClass()) {return true;} return false; } //toString public String toString() { return "topLeft: " + topLeft + " bottomRight" + bottomRight; } //computeArea public float computeArea() { return Math.abs( (topLeft.getX() - bottomRight.getX())*(bottomRight.getY() - topLeft.getY())); } }
However, we all know when one parameter in point equal to NaN, the rectange should not work(like throw errors), how to design it? Thanks.
Advertisement
Answer
You can use the Float.isNan
method:
Rectangle(Point topLeft, Point bottomRight){ if (Float.isNan(topLeft.getX()) || Float.isNan(topLeft.getY()) || Float.isNan(bottomRight.getX()) || Float.isNan(bottomRight.getY())) { throw new IllegalArgumentException("Point contains non-numeric coordinate"); } this.topLeft = topLeft; this.bottomRight = bottomRight; }
Alternatively, you can encapsulate this check in the Point
class by adding a method that will only return true
if both coordinates are not NaN. You would then be able to call that method on both points in the Rectangle
constructor.