// Helene Martin, CSE 142 // Draws several triangles and the length of their sides. import java.awt.*; public class Triangles { public static void main(String[] args) { DrawingPanel p = new DrawingPanel(400, 400); Graphics g = p.getGraphics(); printTriangleFacts(40, 50); printTriangleFacts(40, 85); drawTriangle(g, 20, 20, 40, 60); drawTriangle(g, 200, 140, 40, 85); } // Draws a right triangle with upper left corner at (x, y), width // of width and height of height. // The length of each side is in its middle. public static void drawTriangle(Graphics g, int x, int y, int width, int height) { g.setColor(Color.RED); g.drawLine(x, y, x, y + height); g.drawString(height + "", x, y + height / 2); g.setColor(Color.GREEN); g.drawLine(x, y + height, x + width, y + height); g.drawString(width + "", x + width / 2, y + height); g.setColor(Color.BLUE); g.drawLine(x, y, x + width, y + height); double hyp = hypotenuse(width, height);; g.drawString(round2(hyp, 2) + "", x + width / 2, y + height / 2); } // Returns the length of the hypotenuse of a right triangle with sides // width and height public static double hypotenuse(int width, int height) { return Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2)); } // Calculates and displays right triangle facts public static void printTriangleFacts(int width, int height) { System.out.println("Right triangle facts:"); System.out.println("\twidth: " + width); System.out.println("\theight: " + height); double hypotenuse = hypotenuse(width, height); System.out.println("\thypotenuse: " + hypotenuse); } // Returns value rounded to places places public static double round2(double value, int places) { double rounded = Math.round(value * Math.pow(10, places)) / Math.pow(10, places); return rounded; } }