Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class LineIntersect {
- static class Point {
- float x, y;
- public Point(float x, float y) {
- this.x = x;
- this.y = y;
- }
- public String toString() {
- return String.format("(%.2f, %.2f)", x, y);
- }
- }
- static class Line {
- float slope, intcpt;
- public Line(float slope, float intcpt) {
- this.slope = slope;
- this.intcpt = intcpt;
- }
- public String toString() {
- return String.format("y = %.2fx + %.2f", slope, intcpt);
- }
- }
- /** Calculates the value of y, given a line and an x-coordinate. */
- static float calculateSlopeIntercept(Line line, float x) {
- return line.slope * x + line.intcpt;
- }
- /**
- * Finds the intersection of two lines. If the slopes of the lines are
- * equal, null will be returned.
- */
- static Point findIntersection(Line line1, Line line2) {
- if (line1.slope == line2.slope) {
- return null;
- }
- float x = (line2.intcpt - line1.intcpt) / (line1.slope - line2.slope);
- return new Point(x, calculateSlopeIntercept(line1, x));
- }
- public static void main(String[] args) {
- Line line1 = new Line(1, 3);
- Line line2 = new Line(-2, 12);
- /* Print out the point of intersection. */
- System.out.println("Line #1: " + line1);
- System.out.println("Line #2: " + line2);
- System.out.println("\nIntersection: " + findIntersection(line1, line2));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment