The Math class of the JSL has many methods that we can use. I

advertisement
The Math class of the JSL has many methods that we can use. I listed a few that we may need for the Midterm.
There is a random number generator method named random() that requires 2 parameters to produce a random
number.
You need to give it a range.
You need to give it a starting value. (The default start is 0)
We use the name of the class as the “handle” for every method in the Math class because the methods are ‘static’.
Examples:
int num = (int) (Math.random() * 6);
//this will produce a random number in the range of: 0 to 5
int num = (int) (Math.random() * 6) + 1;
//this will produce a random number in the range of: 1 to 6
int num = (int) (Math.random() * 10) - 5;
//this will produce a random number in the range of: -5 to 4
Note that we use the range number as the multiplier for the method and the start is added to the result.
Since the random number produced is a double, we cast it into an integer.
We will explain all this in class.
The pow (num, exp) method raises a number to a power. The second number is the exponent.
Example:
double answer = Math.pow (4, 3);
//this will return the value of 4 cubed.
double answer = Math.pow (625, 1/4.0);
//this will return the fourth root of 625
The sqrt (num) method calculates the square root of a number
double answer = Math.sqrt (30)
//this will return the square root of 30
Download