Java Reference
In-Depth Information
The preceding code is correct, but it's a bit hard to read, and you'd have to dupli-
cate the same complex math a third time if you wanted to include a third triangle. A
better solution would be to create a method that computes and returns the hypotenuse
length when given the lengths of the two other sides as parameters. Such a method
would look like this:
public static double hypotenuse(double a, double b) {
double c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
return c;
}
This method can be used to craft a more concise and readable
main
method, as
shown here.
1
public class
Triangles {
2
public static void
main(String[] args) {
3 System.out.println("hypotenuse 1 = " + hypotenuse(5, 12));
4 System.out.println("hypotenuse 2 = " + hypotenuse(3, 4));
5 }
6
7
public static double
hypotenuse(
double
a,
double
b) {
8
double
c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
9
return
c;
10 }
11 }
A few variations of this program are possible. For one, it isn't necessary to store the
hypotenuse
method's return value into the variable
c
. If you prefer, you can simply
compute and return the value in one line. In this case, the body of the
hypotenuse
method would become the following:
return Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
Also, some programmers avoid using
Math.pow
for low powers such as 2 and just
manually do the multiplication. Using that approach, the body of the hypotenuse
method would look like this:
return Math.sqrt(a * a + b * b);
Search WWH ::
Custom Search