Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class pointInPolygon {
- public static void main (String[] args) {
- Scanner scanner = new Scanner(System.in);
- System.out.println("The polygon is given by the coordinates of its vertices. Determine if the given point belongs to the area of the polygon.");
- System.out.println("Input number of vertices:");
- int n = 0;
- final int min = 3;
- boolean isIncorrect;
- do {
- isIncorrect = false;
- try {
- n = Integer.parseInt(scanner.nextLine());
- } catch (Exception e) {
- isIncorrect = true;
- System.out.println("Please, enter a positive integer number:");
- }
- if (!isIncorrect && (n < min)) {
- isIncorrect = true;
- System.out.println("There must be more than 2 vertices.");
- }
- } while (isIncorrect);
- float[] arrX = new float [n];
- float[] arrY = new float [n];
- int i;
- for (i = 0 ; i < n; i++){
- System.out.println("Enter coordinates for point " + (i + 1) + ":");
- do {
- isIncorrect = false;
- try {
- arrX[i] = Float.parseFloat(scanner.nextLine());
- } catch (Exception e) {
- isIncorrect = true;
- System.out.println("Please, enter a number:");
- }
- } while (isIncorrect);
- do {
- isIncorrect = false;
- try {
- arrY[i] = Float.parseFloat(scanner.nextLine());
- } catch (Exception e) {
- isIncorrect = true;
- System.out.println("Please, enter a number:");
- }
- } while (isIncorrect);
- }
- System.out.println("Input point coordinates:");
- float x = 0;
- float y = 0;
- do {
- isIncorrect = false;
- try {
- x = Float.parseFloat(scanner.nextLine());
- } catch (Exception e) {
- isIncorrect = true;
- System.out.println("Please, enter a number:");
- }
- }while (isIncorrect);
- do {
- isIncorrect = false;
- try {
- y = Float.parseFloat(scanner.nextLine());
- } catch (Exception e) {
- isIncorrect = true;
- System.out.println("Please, enter a number:");
- }
- } while (isIncorrect);
- scanner.close();
- boolean gotInto = false;
- int j = n - 1 ;
- for (i = 0; i < n; i++) {
- if ((((arrY[i] <= y) && (y <= arrY[j])) || ((arrY[j] <= y) && (y <= arrY[i]))) && (((arrY[j] - arrY[i]) != 0) && (x >= ((arrX[j] - arrX[i]) * (y - arrY[i]) / (arrY[j] - arrY[i]) + arrX[i]))))
- gotInto = !gotInto;
- j++;
- if (j == n)
- j = 0;
- }
- if (gotInto){
- System.out.println("Point belongs to area!");
- }
- else {
- System.out.println("Point doesn't belong to area.");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement