/* This program demonstrates the use of the Math and Random Libraries in Java. * Math is a class available under the java.lang package. It is a static final class, which means it cannot be instantiated. * Random is a class available under the java.util package. It is not static, so it has to be instantiated before use. * This program only demonstrates a few of the available methods for both classes. Please consult the API for the entire list. */ import java.util.Random; import java.util.Scanner; class Libraries { public static void main(String [] args) { Scanner input = new Scanner(System.in); //We now use some of the methods in the Math class //Finding the absolute value of an integer. int num = -20; System.out.println("The absolute value of "+num+" is "+ Math.abs(num)); //Since the Math class is static, we need to refer to the methods using the class name, which is why we say Math.method. //Finding the absolute value of a double. double dnum = -2.873; System.out.println("The absolute value of "+dnum+" is "+ Math.abs(dnum)); //Getting the natural logarithm (base e). // You can also store the result of the method (its return value) in another variable. System.out.println("Enter a double value : "); double val = input.nextDouble(); double logVal = Math.log(val); System.out.println("log "+val+" is "+ logVal); // To raise a number to a particular power. System.out.println("Enter two numbers : "); double x = input.nextDouble(); double y = input.nextDouble(); double result = Math.pow(x,y); System.out.println(x+"^"+y+" is "+result); //To use the Random Number Generator, we need to create an object of the Random Class. // That sets up a random number generator, which is actually a stream of Random numbers. // We can get keep asking the RNG to give us random numbers. Random r1 = new Random(); // This uses the current system time as a seed. // If we want to specify a seed, we can. Then, we pass the seed in as a parameter. // The line would then be: Random r1 = new Random ( 1234); // 1234 is the seed we're using. // To get an integer from the RNG int randomNum = r1.nextInt(); System.out.println("The random number we just got is "+randomNum); // In case we want to generate an integer in a range with a certain upper limit int randomNum1 = r1.nextInt(25); // That line will generate a number in the range [0,24]. If we want to lower the range, subtract the lower limit. // If you want to raise the range, add the lower limit. // For eaxmple, if we wanted to generate a number in the range [1,25], add one to the number generated. System.out.println("The new random number, this one in the range [1,25] is "+randomNum1); // We can also generate doubles. Doubles generated will always be between 0 and 1. // Also, we cannot specify ranges for doubles. double dRandom = r1.nextDouble(); System.out.println("The random double value we just generated is "+ dRandom); } }