import java.awt.geom.Point2D; /** * Provides CS 160, Lab 4 functionality for the Triangle class. * * @author John Paxton * @version October 1, 2008 */ public class Triangle { /** * Create a triangle from 3 points. * @param p1 the first point * @param p2 the second point * @param p3 the third point */ Triangle (Point2D.Double p1, Point2D.Double p2, Point2D.Double p3) { point1 = p1; point2 = p2; point3 = p3; } /** * Calculate and return the perimeter of a triangle * @return the perimeter of a triangle */ public double getPerimeter() { return getLineLength(point1, point2) + getLineLength(point2, point3) + getLineLength(point3, point1); } /** * Calculate the area of a triangle using Heron's rule. * @return the area of a triangle */ public double getArea() { double s = getPerimeter() / 2; return Math.sqrt(s * (s - getLineLength(point1, point2)) * (s - getLineLength(point2, point3)) * (s - getLineLength(point3, point1))); } /** * Calculate and return the length of a line between two points * @param point1 the first point * @param point2 the second point * @return the distance between the two points */ private double getLineLength(Point2D.Double point1, Point2D.Double point2) { double x1 = point1.getX(); double y1 = point1.getY(); double x2 = point2.getX(); double y2 = point2.getY(); return Math.sqrt( (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1) ); } private Point2D.Double point1; // first point of triangle private Point2D.Double point2; // second point of triangle private Point2D.Double point3; // third point of triangle }