MrPolywhirl

Line Intersect

May 5th, 2014
408
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. public class LineIntersect {
  2.     static class Point {
  3.         float x, y;
  4.  
  5.         public Point(float x, float y) {
  6.             this.x = x;
  7.             this.y = y;
  8.         }
  9.  
  10.         public String toString() {
  11.             return String.format("(%.2f, %.2f)", x, y);
  12.         }
  13.     }
  14.  
  15.     static class Line {
  16.         float slope, intcpt;
  17.  
  18.         public Line(float slope, float intcpt) {
  19.             this.slope = slope;
  20.             this.intcpt = intcpt;
  21.         }
  22.  
  23.         public String toString() {
  24.             return String.format("y = %.2fx + %.2f", slope, intcpt);
  25.         }
  26.     }
  27.  
  28.     /** Calculates the value of y, given a line and an x-coordinate. */
  29.     static float calculateSlopeIntercept(Line line, float x) {
  30.         return line.slope * x + line.intcpt;
  31.     }
  32.  
  33.     /**
  34.      * Finds the intersection of two lines. If the slopes of the lines are
  35.      * equal, null will be returned.
  36.      */
  37.     static Point findIntersection(Line line1, Line line2) {
  38.         if (line1.slope == line2.slope) {
  39.             return null;
  40.         }
  41.         float x = (line2.intcpt - line1.intcpt) / (line1.slope - line2.slope);
  42.         return new Point(x, calculateSlopeIntercept(line1, x));
  43.     }
  44.  
  45.     public static void main(String[] args) {
  46.         Line line1 = new Line(1, 3);
  47.         Line line2 = new Line(-2, 12);
  48.  
  49.         /* Print out the point of intersection. */
  50.         System.out.println("Line #1: " + line1);
  51.         System.out.println("Line #2: " + line2);
  52.         System.out.println("\nIntersection: " + findIntersection(line1, line2));
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment