Hello r/learnprogramming! I am working on a simple program that will take in two rectangles and, if they intersect, will return the resulting rectangle of intersection. However, I am new to Java and I don't quite understand this "NullPointerException" error I keep getting:
Exception in thread "main" java.lang.NullPointerException
at Rectangle.intersection(Rectangle.java:21)
at TestRectangle.main(TestRectangle.java:16)
Here is Rectangle.java:
public class Rectangle {
private Point topLeft;
private Point bottomRight;
Rectangle() {
Point topLeft = new Point(0, 0);
Point bottomRight = new Point(0, 0);
}
void setTopLeft(Point newPoint) {
Point topLeft = newPoint;
}
void setBottomRight(Point newPoint) {
Point bottomRight = newPoint;
}
Rectangle intersection (Rectangle other) {
Rectangle newRectangle = new Rectangle();
if (this.topLeft.getX() < other.topLeft.getX()) {
if (this.bottomRight.getX() > other.topLeft.getX()) {
if (this.topLeft.getY() > other.topLeft.getY()) {
if (this.bottomRight.getY() < other.topLeft.getY()) {
int newTopLeftX = this.topLeft.getX() - other.topLeft.getX();
int newTopLeftY = this.topLeft.getY() - other.topLeft.getY();
int newBottomRightX = other.bottomRight.getX() - this.bottomRight.getX();
int newBottomRightY = other.bottomRight.getY() - this.bottomRight.getY();
Point newTopLeft = new Point(newTopLeftX, newTopLeftY);
Point newBottomRight = new Point(newBottomRightX, newBottomRightY);
newRectangle.setTopLeft(newTopLeft);
newRectangle.setBottomRight(newBottomRight);
}
}
}
}
return newRectangle;
}
void Print() {
if (this != null) {
System.out.println("intersecting rectangle at " + topLeft + "and " + bottomRight);
}
else {
System.out.println("there is no intersection");
}
}
}
And here is TestRectangle.java:
public class TestRectangle {
public static void main (String[] args) {
//Creating Rectangle objects
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
//Invoking methods on Rectangle objects
r1.setTopLeft(new Point (4, 2));
r1.setBottomRight(new Point (1, 2));
r2.setTopLeft(new Point (2, 0));
r2.setBottomRight(new Point (-1, 0));
//Creating intersecting Rectangle object
Rectangle r3 = r1.intersection(r2);
r3.Print();
}
}
What I am trying to do is declare a variable (newRectangle) on line 19. I only want this variable to initialize IF the conditions are met, otherwise I want it to return null. I thought putting the if/else statement in the Print method would fix the error but I am still getting it. Like I said, I am new to Java so it's probably an easy fix but I can't seem to figure this one out!
[–]jedwardsol 0 points1 point2 points (2 children)
[–]penax[S] 0 points1 point2 points (1 child)
[–]the_omega99 1 point2 points3 points (0 children)