假设一个平面上有一个三角形。编写程序,提示用户输入三角形的三个点,提示用户输入一个点的x坐标和y坐标,然后判断这个点是否在该三角形内。
package pack2;
import java.util.Scanner;
import javafx.geometry.Point2D;
public class InTriangle {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter three points of a triangle: ");
double x0 = input.nextDouble(), y0 = input.nextDouble();
double x1 = input.nextDouble(), y1 = input.nextDouble();
double x2 = input.nextDouble(), y2 = input.nextDouble();
System.out.print("Enter a point's x- and y-coordinates: ");
System.out.println("The point is "+(isInTriangle(input.nextDouble(),
input.nextDouble(), x0, y0, x1, y1, x2, y2) ? "" : "not ")+"in the triangle");
}
}
//判定是否在三角形内
public static boolean isInTriangle(double x, double y, double x0, double y0,
double x1, double y1, double x2, double y2) {
//三角形的三个点
Point2D p1 = new Point2D(x0, y0);
Point2D p2 = new Point2D(x1, y1);
Point2D p3 = new Point2D(x2, y2);
return Math.abs(getArea(p1, p2, p3) - (getArea(new Point2D(x, y), p2, p3) +
getArea(p1, new Point2D(x, y), p3) + getArea(p1, p2, new Point2D(x, y)))) < 0.00001;
}
//获取面积
public static double getArea(Point2D p1, Point2D p2, Point2D p3) {
double side1 = p1.distance(p3);
double side2 = p1.distance(p2);
double side3 = p2.distance(p3);
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
}