/* Triangle.java * In this file, we implement all the necessary functionality * for triangles. We need to specify the attributes and operations. * The attributes are simply the 3 sides of the triangle. */ public class Triangle { private int shortest; // These attributes could have been double. private int middle; private int longest; // Constructor: Given 3 values, initialize the attributes. To simplify // the implementation, let's assume that the 3 parameters are already // in ascending order. Otherwise we'd have to enumerate every possible // permutation (6 cases) using if statements. public Triangle (int a, int b, int c) { shortest = a; middle = b; longest = c; } // isValid - Is the longest side less than the sum of the other 2 sides? public boolean isValid() { return longest < middle + shortest; } // isEquilateral - We only need to check the sides of extreme length. :) // In math, this is called the "squeeze theorem": If a <= b <= c and you // know that a == c, then b must be equal as well. public boolean isEquilateral() { return longest == shortest; } // Let's assume that an equilateral triangle may also be isosceles. // (It wouldn't be hard to change this assumption.) public boolean isIsosceles() { return longest == middle || middle == shortest; } // Finally, about the angles. Use the pythagorean theorem for right, etc. public boolean isRight() { return longest*longest == middle*middle + shortest*shortest; } public boolean isObtuse() { return longest*longest > middle*middle + shortest*shortest; } // This function performs a calculation and returns a number. public int findPerimeter() { return shortest + middle + longest; } // Finally, it's a nice idea to have a way to print out an object. // We do this by writing a toString() function. // I'll just put the 3 lengths inside parentheses. public String toString() { return "(" + shortest + ", " + middle + ", " + longest + ")"; } }