Using the Math Class
Overview: 2.9.0
- Random numbers are generated with
Math.random()
Math.abs(int)
returns the absolute value of an integer- These methods are defined in
java.lang.Math
- These are
static methods
which means they can be called without creating an objectMath.abs(-33)
would work even though you didn’t create aMath
object- Called using the class name and the dot operator
ClassName.methodName()
- just
methodName()
if called from within the same class
- These are
Math.random
- returns a number between 0.0 and 0.99
-
Use Math.random and cast to int to create a random integer
- A random number between
min
andmax
is defined by the formula(int)(Math.random() * (max-min+1))+min
import java.lang.Math;
public class MyUtilityClass {
/**
Generates a random number between min and max
@param min is the minimum integer value which can be returned
@param max is the maximum integer value which can be returned
@return a random int from min -> max
*/
public static int randInt(int min, int max) {
int range = max - min + 1;
return (int)(Math.random() * range) + min;
}
}
Other functions
Math.abs(int)
- Returns the absolute value of an int input
- int return type
Math.abs(double)
also works- double return type
Math.pow(double, double)
- Returns the first parameter raised to the power of the second power
- double return type
Math.sqrt(double)
- Returns the positive square root of the input
- double return type
Math.random()
- Returns a value within the range [0.0, 1.0)
These methods are on the quick reference sheet!
Summary: 2.9.2
- Static Math methods can be called using
Math.methodName()
- Values from
Math.random
can be manipulated to produce a random int or double in a set range(int)(Math.random() * (max-min+1))+min
creates a random int frommin
tomax
(int)(Math.random() * (10-5+1))+5
creates a random number between 5 and 10
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.