package pack1;
import javafx.geometry.Point2D;
import java.util.Scanner;
public class Area {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter the number of the points: ");
int n = input.nextInt();
System.out.println("Enter the coordinates of the points: ");
System.out.println("The total area is " + getArea(inputData(input, n)));
}
}
// -12 0 -8.5 10 0 11.4 5.5 7.8 6 -5.5 0 -7 -3.5 -13.5
/**返回凸多边形面积*/
public static double getArea(double[][] points) {
Point2D[] point2DS = new Point2D[points.length]; //PointsD数组
for (int i = 0; i < points.length; i++) //用点依次创建Point2D对象
point2DS[i] = new Point2D(points[i][0], points[i][1]);
double area = 0.0; //面积
for (int i = 0; i < point2DS.length - 2; i++)
//凸多边形分为多个三角形,依次求三角形面积之和
area += getTriangleArea(point2DS[0], point2DS[i + 1], point2DS[i + 2]);
return area;
}
/**返回三角形面积*/
public static double getTriangleArea(Point2D...point2DS) {
double side1 = point2DS[0].distance(point2DS[1]);
double side2 = point2DS[0].distance(point2DS[2]);
double side3 = point2DS[1].distance(point2DS[2]);
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
/**输入数据并返回数组列表*/
public static double[][] inputData(Scanner input, int n) {
double[][] points = new double[n][2];
for (int i = 0; i < points.length; i++)
for (int j = 0; j < points[i].length; j++)
points[i][j] = input.nextDouble();
return points;
}
}