Determining if a point is in a triangle

I worked on this watch, trying to use different methods, examining almost every issue. Perhaps this is completely wrong with me, but I feel that my math is correct, but no matter what numbers I enter, I get the same result. My code has gone somewhere, and I have to turn it on by midnight.

This is all so much fun: find out if the dot is in the triangular code. (for beginners)

import java.util.Scanner;

public class PointsTriangle {

    // checks if point entered is within the triangle
    //given points of triangle are (0,0) (0,100) (200,0)
    public static void main (String [] args) {
        //obtain point (x,y) from user
        System.out.print("Enter a point x- and y-coordinates: ");
        Scanner input = new Scanner(System.in);
        double x = input.nextDouble();
        double y = input.nextDouble();

        //find area of triangle with given points
        double ABC = ((0*(100-0  )+0*(0  -0)+200*(0-100))/2.0);
        double PAB = ((x*(0  -100)+0*(100-y)+0  *(y-  0))/2.0);
        double PBC = ((x*(100-0  )+0*(0  -y)+200*(y-100))/2.0);
        double PAC = ((x*(0  -100)+0*(100-y)+200*(y-  0))/2.0);

        boolean isInTriangle = PAB + PBC + PAC == ABC;

        if (isInTriangle)
            System.out.println("The point is in the triangle");
        else
            System.out.println("The point is not in the triangle");
    }//end main
}//end PointsTriangle
+5
source share
2 answers

If you draw an image, you can see that the point should satisfy simple inequalities (below / above / to the right of certain lines). Be "on the edge" come in or go out, I will leave you:

Y > 0 (above the X axis)
X > 0 (to the right of the Y axis)
X + 2* Y < 200 (below the hypotenuse)

Write an if statement from these three, and you are done:

if( (y > 0) && (x > 0) && (x + 2*y < 200) ) 
  System.out.println("The point is in the triangle");
else
  System.out.println("The point is not in the triangle");
+5

; . 3

A(x1, y1) B(x2, y2), C(x3, y3)

double ABC = Math.abs (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2;

, : PBC, APC, ABP.

,

int x1 = 0, y1 = 0;
int x2 = 0, y2 = 100;
int x3 = 200, y3 = 0;

// no need to divide by 2.0 here, since it is not necessary in the equation
double ABC = Math.abs (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2));
double ABP = Math.abs (x1 * (y2 - y) + x2 * (y - y1) + x * (y1 - y2));
double APC = Math.abs (x1 * (y - y3) + x * (y3 - y1) + x3 * (y1 - y));
double PBC = Math.abs (x * (y2 - y3) + x2 * (y3 - y) + x3 * (y - y2));

boolean isInTriangle = ABP + APC + PBC == ABC;
+5

All Articles