1 / 4

Random (1)

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

lorde
Download Presentation

Random (1)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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;

  2. 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

  3. 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?

  4. 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.

More Related