日期:2014-05-20 浏览次数:20721 次
class Point { private double x; private double y; public Point() { } /** * @param x * @param y */ public Point(double x, double y) { this.x = x; this.y = y; } /** * @return the x */ public double getX() { return x; } /** * @param x * the x to set */ public void setX(double x) { this.x = x; } /** * @return the y */ public double getY() { return y; } /** * @param y * the y to set */ public void setY(double y) { this.y = y; } /* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "Point [x=" + x + ", y=" + y + "]"; } } public class Test { public static double getK(Point a, Point b) { if (b.getX() == a.getX()) { return 0; } return (b.getY() - a.getY()) / (b.getX() - a.getX()); } public static Point getPoint(Point a, Point b, Point c, Point d) { Point result = new Point(); double k1, k2; k1 = (b.getY() - a.getY()) / (b.getX() - a.getX()); k2 = (d.getY() - c.getY()) / (d.getX() - c.getX()); result.setX((k1 * a.getX() / k2 - c.getX()) * k2 / (k1 - k2)); result.setY(k1 * (result.getX() - a.getX())); return result; } public static Point[] getPoint(Point a, Point b, double len) { Point[] result = new Point[] { new Point(), new Point() }; double k = getK(b, a); double z = a.getY() - k * a.getX(); if (k >= -1.0 && k <= 1.0) { result[0].setY(a.getY() + len / 2); result[0].setX((result[0].getY() - z) / k); result[1].setY(a.getY() - len / 2); result[1].setX((result[1].getY() - z) / k); } else { result[0].setX(a.getX() + len / 2); result[0].setY(result[0].getX() * k + z); result[1].setX(a.getX() - len / 2); result[1].setY(result[1].getX() * k + z); } return result; } public static void main(String[] args) { Point a = new Point(2, 2); Point b = new Point(5, 4); double len = 2.0; Point[] points = getPoint(a, b, len); for (Point p : points) { System.out.println(p); } } }