Okay I am writing a program that, in the end, will bring up a GUI window and ask the user what type of shape they want to make. The choices are line, circle, ellipse, rectangle, and polygon. When the user selects a shape they are then asked some key information about the shape they want to make.
for instance if they select "circle" it asks "what is the center point's X coordinate"... "what is the Y coordinate"... "what is the radius".... then it prints the circle out and a pop up window says the area of the shape they just made.
The problem I am having is calculating the area of a polygon. I have no problem with any of the user input and the shape prints out just fine but the area for the polygon is usually only correct if it is a square or triangle. Most of the time the area that is output is either double the actual or half of the actual. I am trying to use the formula from the wikipedia page right now and that is:
Area = (1/2)[n-1 Σ i=0](Xi*Yi+1 - Xi+1*Yi)
just go to wikipedia.org and search "Polygon Area" and it's the 1st formula
I tell the user to input each point in clockwise order which is how you are supposed to for this formula to work. If someone could point out what I have done wrong that would be great. the code I am showing here is a modified version with just the polygon class and a main area where you can manipulate the polygon's dimensions.
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class PolygonTest
{
// variables
int[] xPoints;
int[] yPoints;
int numOfPoints;
double area;
String name;
// constructor
public PolygonTest(String n, int[] xs, int[] ys, int p)
{
name = n;
xPoints = xs;
yPoints = ys;
numOfPoints = p;
area = 0;
}
public void paint(Graphics g)
{
g.drawPolygon(xPoints, yPoints, numOfPoints);
}
public void A3draw()
{
JFrame frame = new JFrame("This is a Polygon");
frame.setSize(500,500);
Polygon p = new Polygon(name, xPoints, yPoints, numOfPoints);
frame.add(p);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public double getMeasure()
{
for(int i = 0; i < numOfPoints-2; i++)
{
area += (xPoints[i]*yPoints[i+1])-(xPoints[i+1]*yPoints[i]);
}
area /= 2;
//if they enter points counterclockwise the area will be negative but correct.
if(area < 0)
area *= -1;
return area;
}
public static void main(String[] args)
{
// each point should have its x coord and y coord at the same index
// points should be entered in clockwise order
int[] xPts = {50,100,100,50};
int[] yPts = {50,50,100,100};
// name it whatever
String nameOfPolygon = "Imapolygon";
PolygonTest poly1 = new PolygonTest(nameOfPolygon, xPts, yPts, xPts.length);
poly1.A3draw();
JOptionPane.showMessageDialog(null, "The area of " + poly1.name + " is " + poly1.getMeasure() + " pixels.");
}
}