两条线段知道端点line1(x1,y1)(x2,y2)line2(x3,y3)(x4,y4),判断两条线段是否相交,交点坐标(x,y)

public class LinearEquation {
    private double x1;
    private double x2;
    private double y1;
    private double y2;
    private double x;
    private double y;
    public LinearEquation(double x1, double y1, double x2, double y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }

    public double getK() {
        double k;
        k = (y1 - y2) / (x1 - x2);
        return k;
    }

    public double getB() {
        double b;
        b = y1 - x1 * ((y1 - y2) / (x1 - x2));
        return b;
    }

    public double getX(double k1, double b1, double k2, double b2) {
        x = (b2 - b1) / (k1 - k2);
        return x;
    }

    public double getY(double k1, double b1, double k2, double b2) {
        y = ((b2 - b1) / (k1 - k2)) * k1 + b1;
        return y;
    }

}
<pre name="code" class="java">public class TwoLineIntersection {

    public static void main(String[] args) {
        double x1 = 0, y1 = 0, x2 = 0, y2 = 0, x3 = 0, y3 = 0, x4 = 0, y4 = 0, x = 0, y = 0;
        Scanner input = new Scanner(System.in);
        boolean isEnd = false;
        while (!isEnd)
            try {
                System.out.println("请输入第1条线的两个坐标:");
                x1 = input.nextDouble();
                y1 = input.nextDouble();
                x2 = input.nextDouble();
                y2 = input.nextDouble();
                System.out.println("请输入第2条线的两个坐标:");
                x3 = input.nextDouble();
                y3 = input.nextDouble();
                x4 = input.nextDouble();
                y4 = input.nextDouble();
                isEnd = true;
            } catch (InputMismatchException e) {
                System.out.println("输入错误请按照如下格式重新输入double型的坐标(2 2 0 0)或(2.0 2.0 0 0):");
                input.nextLine();
                isEnd = false;
            }
        LinearEquation lineE1 = new LinearEquation(x1, y1, x2, y2);
        LinearEquation lineE2 = new LinearEquation(x3, y3, x4, y4);
        x = lineE1.getX(lineE1.getK(), lineE1.getB(), lineE2.getK(), lineE2.getB());
        y = lineE1.getY(lineE1.getK(), lineE1.getB(), lineE2.getK(), lineE2.getB());


        if (lineE1.getK() == lineE2.getK()) {
            System.out.println("两线段平行没有交点!!!");
        } else if (y==lineE1.getK()*x+lineE1.getB()&&y==lineE2.getK()*x+lineE2.getB()) {
                System.out.println("两线段的交点是:(" + x + "," + y + ")");
            } else {
                System.out.println("两线段不相交!!长度不够哦!");
            }
        }
}
//运行结果: 
请输入第1条线的两个坐标:
2 2 0 0
请输入第2条线的两个坐标:
0 5 5 0
两线段的交点是:(2.5,2.5)


 
 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值