How to calculate the center of a rectangle in Java

3 Answers

0 votes
public class RectangleCenter {
 
    static class Point {
        double x, y;
 
        Point(double x, double y) {
            this.x = x;
            this.y = y;
        }
    }
 
    static class Rectangle {
        Point topLeft;
        Point bottomRight;
 
        Rectangle(Point topLeft, Point bottomRight) {
            this.topLeft = topLeft;
            this.bottomRight = bottomRight;
        }
    }
 
    static Point getCenter(Rectangle rect) {
        double centerX = (rect.topLeft.x + rect.bottomRight.x) / 2.0;
        double centerY = (rect.topLeft.y + rect.bottomRight.y) / 2.0;
        return new Point(centerX, centerY);
    }
 
    public static void main(String[] args) {
        Rectangle rect = new Rectangle(
            new Point(10.0, 20.0),
            new Point(110.0, 70.0)
        );
 
        Point center = getCenter(rect);
 
        System.out.printf("Center of the rectangle: (%.2f, %.2f)%n", center.x, center.y);
    }
}

  
/*
run:
  
Center of the rectangle: (60.00, 45.00)
  
*/

 



answered Jun 22, 2025 by avibootz
edited Jun 22, 2025 by avibootz
0 votes
import java.awt.Rectangle;
 
public class RectangleCenter {
    public static void main(String[] args) {
        // Create a rectangle with x, y, width, and height
        Rectangle rect = new Rectangle(10, 20, 100, 50);
 
        System.out.println("Center of the rectangle: (" + rect.getCenterX() + ", " + rect.getCenterY() + ")");
    }
}


  
/*
run:
  
Center of the rectangle: (60.0, 45.0)
  
*/

 



answered Jun 22, 2025 by avibootz
edited Jun 22, 2025 by avibootz
0 votes
import java.awt.geom.Rectangle2D;

public class RectangleCenter {
    public static void main(String[] args) {
        // Create a Rectangle2D object
        Rectangle2D rectangle = new Rectangle2D.Double(10, 20, 100, 50); // x, y, width, height

        // Calculate the center coordinates
        double centerX = rectangle.getCenterX();
        double centerY = rectangle.getCenterY();

        System.out.println("Center of the rectangle:");
        System.out.println("X: " + centerX);
        System.out.println("Y: " + centerY);
    }
}


 
/*
run:
 
Center of the rectangle:
X: 60.0
Y: 45.0
 
*/

 



answered Jun 22, 2025 by avibootz

Related questions

1 answer 106 views
1 answer 80 views
1 answer 93 views
2 answers 135 views
...