// Helene Martin, CSE 142 // Calculates the hypotenuse of a right triangle and displays it on // a DrawingPanel and the console. import java.awt.*; public class Triangles { public static void main(String[] args) { DrawingPanel panel = new DrawingPanel(400, 400); Graphics g = panel.getGraphics(); drawRightTriangle(g, 50, 50, 80, 60); drawRightTriangle(g, 170, 20, 50, 50); drawRightTriangle(g, 10, 200, 150, 133); printTriangleFact(100, 200); printTriangleFact(150, 200); } // Draws a scalable, translatable right triangle with labeled sides public static void drawRightTriangle(Graphics g, int x, int y, int width, int height) { g.drawLine(x, y, x, y + height); g.drawString(height + "", x, y + height / 2); g.drawLine(x, y + height, x + width, y + height); g.drawString("" + width, x + width / 2, y + height); g.drawLine(x, y, x + width, y + height); double hyp = hypotenuse(width, height); g.drawString("hyp: " + round(hyp), x + width / 2, y + height / 2); } // Calculates and displays right triangle facts public static void printTriangleFact(int width, int height) { System.out.println("Right triangle facts:"); System.out.println("\twidth: " + width); System.out.println("\theight: " + height); System.out.println("\thypotenuse: " + round(hypotenuse(width, height))); } // Given a decimal value, return it rounded to digits places public static double round(double value, int digits) { return (int) (value * Math.pow(10, digits)) / (double)Math.pow(10, digits); } // Given a width and a height, compute the hypotenuse of the triangle. public static double hypotenuse(int w, int h) { double hyp = Math.sqrt(Math.pow(w, 2) + Math.pow(h, 2)); return hyp; // alternately: return Math.sqrt(Math.pow(w, 2) + Math.pow(h, 2)); } }