Page 193 - Introduction to Programming with Java: A Problem Solving Approach
P. 193
5.3 Math Class 159
/******************************************************************
*
FindHypotenuse.java
Dean & Dean
This program computes the hypotenuse of a right triangle.
******************************************************************/
*
*
*
import java.util.Scanner;
public class FindHypotenuse
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
double base;
double height;
double hypotenuse;
System.out.print("Enter right triangle base: ");
base = stdIn.nextDouble();
System.out.print("Enter right triangle height: ");
height = stdIn.nextDouble();
hypotenuse = Math.sqrt(base * base + height * height);
Apago PDF Enhancer
System.out.println("Hypotenuse length = " + hypotenuse);
}
// end main
}
// end FindHypotenuse
call to Math class’s sqrt method
Sample session:
Enter right triangle base: 3.0
Enter right triangle height: 4.0
Hypotenuse length = 5.0
Figure 5.3 FindHypotenuse program demonstrates use of one of Java’s pre-built math functions Named Constants
The Math class also contains double values for two important named constants: PI = 3.14159265358979323846
E = 2.7182818284590452354
PI and E are standard mathematical constants. PI is the ratio of a circle’s perimeter to its diameter. E is Euler’s number, the base for natural logarithm calculations. The names PI and E are in all uppercase characters, because that’s standard style for named constants. Constants have fixed values, and if you at- tempt to assign a value to them, you’ll get a compilation error. Just as Math’s methods are called class meth- ods, these constants are called class constants, and you access them through the Math class name. In other words, if you need , specify Math.PI.
⎧ ⎨ ⎩