Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Name:
- * Date:
- * Course Number:
- * Course Name:
- * Problem Number:
- * Email:
- * Short Description of the Problem
- */
- import java.util.Scanner;
- import java.lang.*;
- public class polygonHW {
- //**********************************************
- public static void main(String[] args) {
- int size;
- Scanner sc = new Scanner(System.in);
- System.out.print("Enter number of points (must be more than 3)");
- size = sc.nextInt();
- Double[] x = new Double[size];
- Double[] y = new Double[size];
- getPoints(sc, x,y);
- printPoints(x,y);
- printArea(x,y);
- }
- // Important stuff is in this method
- private static void printArea(Double[] x, Double[] y) {
- double theta = 0;
- double hyp = 0;
- double base = 0;
- double height = 0;
- double Area = 0;
- //calls orient method
- x = orientArr(x);
- y = orientArr(y);
- //loop runs two less times than the array length, always starts at [1] because [0] is now the origin (0,0)
- //The idea is that one point will always be 0,0 so we just need to worry about two points at a time
- for(int i = 1; i < x.length -1 ; i++ )
- {
- base = simpleDist(x[i] , y[i]);
- hyp = simpleDist(x[i+1] , y[i+1]);
- //subtracts arctan of theta point 1 with respect to origin from theta point 2 with respect to origin, gives us the angle of the triangle near the origin
- theta = Math.atan2(y[i], x[i]) - Math.atan2(y[i+1], x[i+1]);
- height = Math.sin(theta) * hyp;
- //Heron's Formula I think he said he wanted to return an error if this produces a negative number
- // not sure though, it might be more complicated
- Area += (base * height)/2;
- }
- System.out.println("Area = " + Area);
- }
- //sets points stored at [0] as origin
- private static Double[] orientArr(Double[] x) {
- double xCancel = x[0];
- for(int i = 0; i < x.length ; i++ )
- {
- x[i] -= xCancel;
- }
- return x;
- }
- // returns a point's distance from origin
- private static double simpleDist(Double x, Double y) {
- return Math.sqrt(Math.pow(x,2d) + Math.pow(y,2));
- }
- private static void printPoints(Double[] x, Double[] y) {
- System.out.println("Collected Points");
- for(int i = 0; i < x.length ; i++ ) {
- System.out.println(x[i] +" , " + y[i]);
- }
- }
- private static void getPoints(Scanner sc, Double[] x, Double[] y) {
- for(int i = 0; i < x.length ; i++ ) {
- x[i] = sc.nextDouble();
- y[i] = sc.nextDouble();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement