|
| 1 | +package ch_11; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Scanner; |
| 5 | + |
| 6 | +/** |
| 7 | + * 11.15 (Area of a convex polygon) A polygon is convex if it contains any line segments |
| 8 | + * that connects two points of the polygon. |
| 9 | + * <p> |
| 10 | + * Write a program that prompts the user to enter the number of points in a convex polygon, then enter the points |
| 11 | + * clockwise, |
| 12 | + * and display the area of the polygon. |
| 13 | + * <p> |
| 14 | + * Here is a sample run of the program: |
| 15 | + * Enter the number of the points: 7 |
| 16 | + * Enter the coordinates of the points: |
| 17 | + * -12 0 -8.5 10 0 11.4 5.5 7.8 6 -5.5 0 -7 -3.5 -3.5 |
| 18 | + * The total area is 250.075 |
| 19 | + */ |
| 20 | +public class Exercise11_15 { |
| 21 | + public static void main(String[] args) { |
| 22 | + Scanner in = new Scanner(System.in); |
| 23 | + |
| 24 | + System.out.print("Enter the number of points: "); |
| 25 | + int numPoints = in.nextInt(); |
| 26 | + |
| 27 | + ArrayList<double[]> pts = new ArrayList<>(); |
| 28 | + |
| 29 | + System.out.print("Enter the coordinates of the points in the convex polygon: "); |
| 30 | + |
| 31 | + for (int i = 0; i < numPoints; i++) { |
| 32 | + double[] pt = new double[2]; |
| 33 | + for (int xy = 0; xy < 2; xy++) { |
| 34 | + pt[xy] = in.nextDouble(); |
| 35 | + } |
| 36 | + pts.add(pt); |
| 37 | + } |
| 38 | + |
| 39 | + System.out.print("The area of the convex polygon is "); |
| 40 | + System.out.println(getAreaConvexPolygon(pts) + ""); |
| 41 | + |
| 42 | + in.close(); |
| 43 | + |
| 44 | + } |
| 45 | + |
| 46 | + static double getAreaConvexPolygon(ArrayList<double[]> pts) { |
| 47 | + double[] lastPoint = pts.get(pts.size() - 1); |
| 48 | + double[] firstPoint = pts.get(0); |
| 49 | + double operand1 = lastPoint[0] * firstPoint[1]; // xn * y1 |
| 50 | + for (int i = 0; i < pts.size() - 1; i++) { |
| 51 | + double[] pt = pts.get(i); |
| 52 | + double[] nextPt = pts.get(i + 1); |
| 53 | + operand1 += pt[0] * nextPt[1]; // x1 * y2 + x2 * y3 + x(n) * y(n+1) + {x(n) * y1} |
| 54 | + } |
| 55 | + double operand2 = lastPoint[1] * firstPoint[0]; // yn * x1 |
| 56 | + for (int i = 0; i < pts.size() - 1; i++) { |
| 57 | + double[] pt = pts.get(i); |
| 58 | + double[] nextPt = pts.get(i + 1); |
| 59 | + operand2 += pt[1] * nextPt[0]; // y1 * x2 + y2 * x3 + y(n) + x(n+1) + {y(n) * x1} |
| 60 | + |
| 61 | + } |
| 62 | + return Math.abs((operand1 - operand2) * 0.5); |
| 63 | + |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments