Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to programming in java Lecture 16 Random.

Similar presentations


Presentation on theme: "Introduction to programming in java Lecture 16 Random."— Presentation transcript:

1 Introduction to programming in java Lecture 16 Random

2 Introduction Programs frequently need random numbers. – A card game uses random numbers to create a shuffled deck of cards. – A dice game uses random numbers to simulate a throw. – Many activities in the real world (such as traffic on a highway system) appear to be random, and a program that models them must use random numbers.

3 Random Number A single die can be regarded as a random number generator that selects a number from the range 1 through 6, and each number is equally likely. The same is true for a second throw of the die. The outcome of the first throw does not affect the outcome of the second throw (or of any other throw).

4 The Random class The Random class can be used in programs that need random numbers. Random is part of the java.util package.

5 The Random class (Cont…) A Random object is started out with a seed value which determines the sequence of numbers it will produce. Every Random object started with the same seed value will produce the same sequence of numbers. There are two constructors for Random objects:

6 The Random class (Cont…) Random() — Creates a new random number generator using a seed based on the current time. Random(long seed) — Creates a new random number generator based on a specific seed value.

7 The Random class (Cont…) Here is an example of constructing a random number generator: Random rand = new Random(); Now the methods of the Random class can be used with rand.

8 nextInt() Here are two methods (out of several) that Random objects provide. The second method is the one most often used.

9 Die Toss Program with out Seed

10 Die Toss Program with Seed

11 Floating Point Random Methods float nextFloat() — Returns a pseudorandom, floating point value in the range 0.0 up to but not including 1.0. double nextDouble() — Returns a pseudorandom, double-precision value in the range 0.0 up to but not including 1.0.

12 More Random Methods long nextLong() — Returns a pseudorandom, uniformly distributed long value. All possible long values, both positive and negative, are in the range of values returned. boolean nextBoolean() — Returns a pseudorandom boolean value.

13 Practice Question Write a program which generators password for the user. Password should be consist of small letters, capital letters and numbers.

14


Download ppt "Introduction to programming in java Lecture 16 Random."

Similar presentations


Ads by Google