Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Name: Philip Crafts/ Luis Calvao
- * Date: 9/22/17
- * Course Number: CSC 220
- * Course Name: Data Structures and Algorithims
- * Problem Number: N/A
- * Email: prcrafts@student.stcc.edu / lccalvao@student.stcc.edu
- * Returns the area of a convex polygon from points entered clockwise
- */
- import java.util.Scanner;
- public class polygonHW {
- private static void process(Scanner sc, String args[]) {
- // Code here is merely a sample
- int size = 0;
- while(size < 3)
- {
- 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];
- System.out.println("Enter points in Rectangular form (seperated by spaces not commas)");
- getPoints(sc, x,y);
- printPoints(x,y);
- printArea(x,y);
- sc.nextLine();
- }
- private static boolean doThisAgain(Scanner sc, String prompt) {
- System.out.print(prompt);
- String doOver = sc.nextLine();
- return doOver.equalsIgnoreCase("Y");
- }
- public static void main(String args[]) {
- final String TITLE = "Crafts/Calvao polygonHW";
- final String CONTINUE_PROMPT = "Do this again? [y/N] ";
- System.out.println("Welcome to " + TITLE);
- Scanner sc = new Scanner(System.in);
- do {
- process(sc, args);
- } while (doThisAgain(sc, CONTINUE_PROMPT));
- sc.close();
- System.out.println("Thank you for using " + TITLE);
- }
- private static void printArea(Double[] x, Double[] y) {
- double theta = 0;
- double hyp = 0;
- double base = 0;
- double height = 0;
- double Area = 0;
- double heronCheck = 0;
- x = orientArr(x);
- y = orientArr(y);
- for(int i = 1; i < x.length -1 ; i++ )
- {
- base = simpleDist(x[i] , y[i]);
- hyp = simpleDist(x[i+1] , y[i+1]);
- theta = Math.atan2(y[i], x[i]) - Math.atan2(y[i+1], x[i+1]);
- height = Math.sin(theta) * hyp;
- heronCheck = (base * height)/2;
- if(heronCheck <= 0)
- {
- System.out.println("not a convex polygon");
- return;
- }
- Area += heronCheck;
- }
- System.out.printf("Area = %.2f\n", Area);
- //System.out.print("\n");
- }
- //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;
- }
- 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) {
- int hold;
- for(int i = 0; i < x.length ; i++ ) {
- hold = i+1;
- System.out.println("point " + hold + ": ");
- x[i] = sc.nextDouble();
- y[i] = sc.nextDouble();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement