Java Program to Check Whether a Given Point Lies Inside a Triangle or not
import java.awt.Point;
import static java.lang.Math.*;
public class Main
{
public static void main(String[] args)
{
//Coordinates of the triangle
Point a = new Point(0,0);
Point b = new Point(20,0);
Point c = new Point(10,30);
//Coordinates of the Point
Point p = new Point(10,15);
// Checks if the point lies in
if(checkPointLoc(a,b,c,p))
System.out.println("The point lies inside the triangle");
else
System.out.println("The point does not lie inside the triangle");
}
// Checks if the areas of the three small triangles add upto the primary triangle
static boolean checkPointLoc(Point a, Point b, Point c, Point p)
{
double primaryTriangleAr = AreaOfTriangle(a,b,c);
double area1 = AreaOfTriangle(a,b,p);
double area2 = AreaOfTriangle(a,p,c);
double area3 = AreaOfTriangle(p,b,c);
if(primaryTriangleAr==area1+area2+area3)
return true;
return false;
}
// Calculates the area of the triangle
static double AreaOfTriangle(Point A, Point B, Point C)
{
return Math.abs((A.x*(B.y-C.y) + B.x*(C.y-A.y)+ C.x*(A.y-B.y))/2.0);
}
}
Output:
The point lies inside the triangle
