The Math class allows you to perform common math functions --- like taking the square root or raising to a power. Math doesn't store any data --- it just does calculation. Math is an example of a static class. You don't need to create a Math object to call Math's methods.When an item is qualified by the keyword static, there is only one of these items per class. There can be only one copy of a static class, so you don't have to create an object of that class before using it.
Example 1: Using the Math class for simple calculations.
double z = Math.sqrt(y); // find the square root of y double w = Math.min(y, z); // find the minimum of the values in y and z System.out.println(Math.abs(x)); // output the absolute value of xThe Math class also has some important mathematical constants such as pi (Math.PI) and e (Math.E).
Many real-world problems involve probabilities---flipping a coin, rolling a die or picking an item at random from a bin. The Java Random class allows us to solve these types of problems by producing values "at random". To use the Random class, you must first create (instantiate) an object of type Random before calling its methods.
Example 2: Create an object of type Random and ask it to give you some "random" numbers:
Random generator = new Random( ); int x = generator.nextInt(); // "random" integer double y = generator.nextDouble(); // "random" double in [0, 1) x = generator.nextInt(10); //"random" integer between 0 and 9This particular Random object is called generator.
Exercise 1: How would you write code to flip a coin?Ans: A coin can either be "heads" or "tails", so we need to choose between two random values.
Random coinFlipper = new Random(); System.out.println("Flipping gives (0 for heads, 1 for tails): " + coinFlipper.nextInt(2));Exercise 2: How would you write code to roll a die?
Ans: A die has values from 1 to 6:
Random dieRoll = new Random(); System.out.println("First roll is " + (dieRoll.nextInt(6) + 1)); System.out.println("Second roll is " + (dieRoll.nextInt(6) + 1));Key point:
import java.util.*;the top of your program after the package declaration.
Exercise 3: How would you find the maximum of 3 random integers between 0 and 99?
Random rand = new Random(); int maxSoFar = rand.nextInt(100); maxSoFar = Math.max(maxSoFar, rand.nextInt(100)); maxSoFar = Math.max(maxSoFar, rand.nextInt(100));
Exercise 4: How would you find the average of 3 random integers between 0 and 99?
Random rand = new Random(); int total = rand.nextInt(100); total += rand.nextInt(100); total += rand.nextInt(100); System.out.println("The average is " + (double)total/3);Exercise 5: Why weren't parentheses needed in the expression total/3 in Exercise 4?