Compute the area of the specified polygon. - Java java.lang

Java examples for java.lang:Math Geometry Shape

Description

Compute the area of the specified polygon.

Demo Code


//package com.java2s;

public class Main {
    /**//from   w w  w  .  j  a v  a2s. c o m
     * Compute the area of the specified polygon.
     *
     * @param x X coordinates of polygon.
     * @param y Y coordinates of polygon.
     * @return Area of specified polygon.
     */
    public static double computePolygonArea(double[] x, double[] y) {
        int n = x.length;

        double area = 0.0;
        for (int i = 0; i < n - 1; i++) {
            area += (x[i] * y[i + 1]) - (x[i + 1] * y[i]);
        }
        area += (x[n - 1] * y[0]) - (x[0] * y[n - 1]);

        area *= 0.5;

        return area;
    }

    /**
     * Compute the area of the specified polygon.
     *
     * @param xy Geometry of polygon [x,y,...]
     * @return Area of specified polygon.
     */
    public static double computePolygonArea(double[] xy) {
        int n = xy.length;

        double area = 0.0;
        for (int i = 0; i < n - 2; i += 2) {
            area += (xy[i] * xy[i + 3]) - (xy[i + 2] * xy[i + 1]);
        }
        area += (xy[xy.length - 2] * xy[1]) - (xy[0] * xy[xy.length - 1]);

        area *= 0.5;

        return area;
    }
}

Related Tutorials