/* * ========================================================= * Definition of class LineSegment: * * A line segment is defined by the (x,y) coordinates of * its two end points. * * Written By : Mark Austin October 1997 * ========================================================= */ public class LineSegment { protected Point p1, p2; // points defining the LineSegment // Constructor method : just create instance of class. public LineSegment() { } // Create instance of class and set (x,y) coordinates. public LineSegment( double dX1, double dY1, double dX2, double dY2 ) { setLineSegment( dX1, dY1, dX2, dY2 ); } // Set x and y coordinates of LineSegment. public void setLineSegment( double dX1, double dY1, double dX2, double dY2 ) { p1 = new Point( dX1, dY1 ); p2 = new Point( dX2, dY2 ); } // Get end points 1 and 2. public Point getPoint1() { return p1; } public Point getPoint2() { return p2; } // Print details of line segment. public void printSegment() { System.out.println("Line Segment"); System.out.println("Point 1 : (x,y) = " + p1.toString() ); System.out.println("Point 2 : (x,y) = " + p2.toString() ); } // Compute length of line segment. public double segmentLength() { double dLength; dLength = (p1.getX() - p2.getX())*(p1.getX() - p2.getX()) + (p1.getY() - p2.getY())*(p1.getY() - p2.getY()); return ((double) Math.sqrt(dLength)); } // Exercise methods in line segment class. public static void main( String args[] ) { double dX, dY; System.out.println("LineSegment test program"); System.out.println("==============================="); // Create two new line segments. LineSegment s1 = new LineSegment(); s1.setLineSegment( 1.0, 1.0, 4.0, 5.0 ); LineSegment s2 = new LineSegment( 1.5, 1.5, 1.5, 4.5 ); // Print details of line segments. s1.printSegment(); s2.printSegment(); // Compute length of line segments. System.out.println("Segment1 has length : " + s1.segmentLength()); System.out.println("Segment2 has length : " + s2.segmentLength()); // End of exercise. System.out.println("==============================="); System.out.println("End of LineSegment test program"); } }