给定一个从点 p0( x0, y0) 到 pl( xl, pl) 的有向线段,可以使用下面的条件来确定点 p2( x2, y2) 是在线段的左侧、右侧,或者在该直线上(见下图) :
编写一个程序,提示用户输入三个点 p0、 p1 和 p2, 显示 p2 是否在从 p0 到 p1 的线段左
侧、右侧,或者在该直线上。
package pack2;
import java.util.Scanner;
import javafx.geometry.Point2D;
public class LocationOfPoint {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter three points for p0, p1, and p2: ");
//从控制台接受x, y 坐标后创建Point2D对象
Point2D p0 = new Point2D(input.nextDouble(), input.nextDouble());
Point2D p1 = new Point2D(input.nextDouble(), input.nextDouble());
Point2D p2 = new Point2D(input.nextDouble(), input.nextDouble());
System.out.println(getLocation(p0, p1, p2));
}
}
//点的位置
public static String getLocation(Point2D p0, Point2D p1, Point2D p2) {
double k = (p1.getX() - p0.getX()) * (p2.getY() - p0.getY()) -
(p2.getX() - p0.getX()) * (p1.getY() - p0.getY());
if(Math.abs(k) < 0.00001) //条件 == 0 时(浮点值有精度差异,用近似值表示等于0)
return String.format("(%.1f, %.1f) is on the line from (%.1f, %.1f) to "+
"(%.1f, %.1f)", p2.getX(), p2.getY(),p0.getX(), p0.getY(), p1.getX(),
p1.getY());
else //条件 > 或 < 0 时
return String.format("(%.1f, %.1f) is on the "+(k > 0 ? "left" : "right")+
" side of the line from (%.1f, %.1f) to (%.1f, %.1f)",
p2.getX(), p2.getY(), p0.getX(), p0.getY(), p1.getX(), p1.getY());
}
}