50 likes | 127 Views
Random (1). Random class contains a method to generate random numbers of integer and double type Note : before using Random class, you should add following line in the top of the source file to import Random class import java.util.Random;. Random (2). Create an object of Random class
E N D
Random (1) • Random class contains a method to generate random numbers of integer and double type Note: before using Random class, you should add following line in the top of the source file to import Random class import java.util.Random;
Random (2) • Create an object of Random class Random rand = new Random(); • Random class contains following methods nextInt( int num ); This method randomly returns one of integers between 0 to num-1 nextDouble( ); This method randomly returns one of doubles between 0.0 to 1.0
Random (3) • Example import java.util.Random; public class ExampleRandom { public static void main (String[] args) { Random rand = new Random( ); System.out.println( r.nextInt( 10 ) ); System.out.println( r.nextInt( 10 ) ); System.out.println( r.nextInt( 10 ) ); System.out.println( r.nextDouble( ) ); System.out.println( r.nextDouble( ) ); } } What is the output from this program? What if run again?
Exercise • Let’s create a game • Guessing Number Game (download GuessNumberGame.java) • A player will guess the number that Java randomly generates • Java randomly generates one number (let’s call it ‘answer’) • If a player guesses the number which is smaller or larger than the answer, then print out the message to instruct the player • If a player correctly guess the number, then print out how many times the player guesses.