title: Computing area of a polygon in Java
body: <p>I have a class called SimplePolygon that creates a polygon with coordinates provided by the user. I am trying to define a method to compute the area of the polygon. It's an assignment and course instructor wants us to use the following formula to compute the area.</p>
  
  <p><img src="https://i.stack.imgur.com/vOdn6.png" alt="Formula for polygon area"></p>
  
  <p>I can use either formula. I chose the right one.</p>
  
  <p>My code gives me the wrong area. I don't know what's wrong.</p>
  
  <pre><code>public class SimplePolygon implements Polygon {
  
    protected int n; // number of vertices of the polygon
    protected Point2D.Double[] vertices; // vertices[0..n-1] around the polygon
  
    public double area() throws NonSimplePolygonException {
      try 
      {
          if(isSimple()==false)
              throw new NonSimplePolygonException();
          else
          {
              double sum = 0;
              for(int i = 0; i &lt; vertices.length - 1; i++)
                  if(i == 0)
                      sum += vertices[i].x * (vertices[i+1].y - vertices[vertices.length - 1].y);
                  else
                      sum += vertices[i].x * (vertices[i+1].y - vertices[i-1].y);
  
              double area = 0.5 * Math.abs(sum);
              return area;
          }
      }
  
      catch(NonSimplePolygonException e)
      {
          System.out.println("The Polygon is not simple.");
      }
  
      return 0.0;
  
  }
  </code></pre>
  
  <p>The following is a tester code. The polygon is a rectangle with area 2, but the output is 2.5</p>
  
  <pre><code>    Point2D.Double a = new Point2D.Double(1,1);
      Point2D.Double b = new Point2D.Double(3,1);
      Point2D.Double c = new Point2D.Double(3,2);
      Point2D.Double d = new Point2D.Double(1,2);
  
      SimplePolygon poly = new SimplePolygon(4);
      poly.vertices[0] = a;
      poly.vertices[1] = b;
      poly.vertices[2] = c;
      poly.vertices[3] = d;
  
      System.out.println(poly.area());
  </code></pre>