Java Reference
In-Depth Information
was trying to state the Pythagorean theorem, although it's not clear whether the writers
were bad at math or whether they were making a comment about the value of a
diploma. In an episode of The Simpsons, Homer repeats the Scarecrow's mistaken for-
mula after putting on a pair of Henry Kissinger's glasses that he finds in a bathroom at
the Springfield nuclear power plant.
The correct Pythagorean theorem refers only to right triangles and says that the
length of the hypotenuse of a right triangle is equal to the square root of the sums of
the squares of the two remaining sides. If you know the lengths of two sides a and b
of a right triangle and want to find the length of the third side c, you compute it as
follows:
a 2
b 2
c
= 2
+
Common Programming Error
Ignoring the Returned Value
When you call a method that returns a value, the expectation is that you'll do
something with the value that's returned. You can print it, store it in a variable, or
use it as part of a larger expression. It is legal (but unwise) to simply call the
method and ignore the value being returned from it:
sum(1000); // doesn't do anything
The preceding call doesn't print the sum or have any noticeable effect. If you
want the value printed, you must include a println statement:
int answer = sum(1000); // better
System.out.println("Sum up to 1000 is " + answer);
A shorter form of the fixed code would be the following:
System.out.println("Sum up to 1000 is " + sum(1000));
Say you want to print out the lengths of the hypotenuses of two right triangles, one
with side lengths of 5 and 12, and the other with side lengths of 3 and 4. You could
write code such as the following:
double c1 = Math.sqrt(Math.pow(5, 2) + Math.pow(12, 2));
System.out.println("hypotenuse 1 = " + c1);
double c2 = Math.sqrt(Math.pow(3, 2) + Math.pow(4, 2));
System.out.println("hypotenuse 2 = " + c2);
 
Search WWH ::




Custom Search