Line.java |
| /* Line.java Stewart Fleming March 2001 Implements requirements for measurement system 11.2 Line Updated by James Little for cosc 241 exercise 2 8/3/01. And again for exercise 2 15/3/01. */ package jlittle_ex2; /** * Represents a line with the equation Ax + By + C = 0 */ public class Line { /** a, b and c represent the line in parametric form. Ax + By + c = 0 This is a more efficient representation for calculations. The gradient specified in requirement 11.2.1 is: m = -A/B */ private double a, b, c; /** the start and end points of the line */ Point startPt, endPt; /** Construct an empty line */ Line(){ a = b = c = 0.0; } // end of Line /** Construct a line with specific coefficients */ Line(int xCoeff, int yCoeff, int cOffset) { a = xCoeff; b = yCoeff; c = cOffset; } // end of constructor /** * Construct a line between two points. * Requirement 11.2.2 */ Line(Point pt1, Point pt2) { // calculate the coefficients for the line between the points a = (double) (pt2.getY() - pt1.getY()); b = (double) (pt1.getX() - pt2.getX()); c = (-a * (double) pt1.getX()) - (b * (double) pt1.getY()); // set the start and end points of the line startPt = pt1; endPt = pt2; } // end of constructor /** * Indicate if a point lies on the line. * Requirement 11.2.7 */ public boolean containsPoint(Point pt) { return ((a * (double) pt.getX()) + (b * (double) pt.getY()) + c == 0.0); } // end containsPoint method /** * Indicate if this line intersects with the line specified. * This line: Ax+ By + C = 0 * Line1: A'x + B'y + c' = 0 * The lines do not intersect if AB' - A'B = 0. * Otherwise the intersection point is: * y = (A'C - AC') / (AB' - A'B) * x = (BC' - B'C) / (AB' - A'B) * Requirement 11.2.8 */ public boolean intersects(Line line1, Point intersectPt) { double denom, x, y; // nobody appeared to be using denom so I thought I would use it. denom = ((a * line1.b) - (line1.a * b)); // if AB' - A'B = 0, then there is no intercept, and I want to return false if(denom!=0.0){ x = ((b * line1.c) - (line1.b * c)) / ((a * line1.b) - (line1.a * b)); y = ((line1.a * c) - (a * line1.c)) / ((a * line1.b) - (line1.a * b)); intersectPt.setX((int) x); intersectPt.setY((int) y); return true; } else return false; }// end intersects method /** Indicates if the line is EXACTLY horizontal */ public boolean isHorizontal() { return (a == 0.0); } // end isHorizontal method /** Indicates if the line is EXACTLY vertical */ public boolean isVertical() { return (b == 0.0); } // end isVertical method } // end of class Line |
James Little |