Essays /

13 Ch05 2 Random Essay

Essay preview

Building Java Programs
Chapter 5
Lecture 5-2: Random Numbers
reading: 5.1 - 5.2
self-check: #8 - 17
exercises: #3 - 6, 10, 12
videos: Ch. 5 #1-2

1
Copyright 2008 by Pearson Education

The Random class
A Random object generates pseudo-random* numbers.
Class Random is found in the java.util package.
import java.util.*;
Method name Description
nextInt()
returns a random integer
nextInt(max) returns a random integer in the range [0, max)
in other words, 0 to max-1 inclusive
nextDouble() returns a random real number in the range [0.0, 1.0)

Example:
Random rand = new Random();
int randomNumber = rand.nextInt(10);

// 0-9

2
Copyright 2008 by Pearson Education

Generating random numbers
Common usage: to get a random number from 1 to N
int n = rand.nextInt(20) + 1;

// 1-20 inclusive

To get a number in arbitrary range [min, max] inclusive:
nextInt(size of range) + min
...

Read more

Keywords

-1 -2 -20 -9 0 0.0 1 1.0 1.5 10 100 11 112 12 13 14 17 19 2 2.5 20 2008 24 25 256 266 280 3 4 4.0 5 5.1 5.2 50 51 6 60 7 8 9 answer arbitrari arg ask askquest build ch ch05 chapter check class code combin come common consol console.nextint copyright correct declar descript dice doubl educ els exampl exercis fencepost first follow found game generat get given gpa guess import inclus incorrect int integ java java.util last lastcorrect lectur loop main map max method min modifi multipl multiplicationtutor n name new nextdoubl nextint num1 num2 number object one outsid packag paper pearson pick play possibl problem program pseudo pseudo-random public pull question r rand rand.nextdouble rand.nextint random random1 random2 random3 randomgpa randomnumb rang reach read real result return right rock rock-paper-scissor roll roll1 roll2 scanner scissor score self self-check set side simul size solut solv static stop string sum system.in system.out.print system.out.println tri tutor two type usag use user valu video void won word would write wrong