{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

05-random-numbers-and-parse

# 05-random-numbers-and-parse - • To get a random double...

This preview shows pages 1–9. Sign up to view the full content.

RANDOM NUMBERS IN JAVA ISE 208: Intermediate Programming SUNY at Stony Brook

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Computers cannot generate truly random numbers They are deterministic A given sequence of input always generates the exact same result True randomness only results from natural sources
We can cheat to get a different sequence of “random” values each time we need one These pseudorandom values are the best we can get without a true source of randomness Java’s Random class lets us generate pseudorandom sequences of numbers. ..

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
The Random class is found in the java.util package When we create a new Random object, it is automatically seeded with the system time Separate Random instances have different creation times, so they generate different “random” sequences Creation: Random r = new Random(); THE RANDOM CLASS
RETRIEVING RANDOM VALUES To get a random integer, use the nextInt() method: int r = myRandom.nextInt(n); This returns a random integer value in the range 0–(n-1)

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
RETRIEVING VALUES (II)

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: • To get a random double, use the nextDouble() method: double r = myRandom.nextDouble(); • This returns a random double value between 0 and 1.0 • Multiply this number by a value n to get a double between 0 and n : double myValue = myRandom.nextDouble() * 5; This generates a random double between 0.0 and 5.0 ODDS & ENDS: CONVERTING STRINGS TO INTS FROM STRING TO INT • Use the Integer.parseInt() utility method to convert a sequence of digit characters into the equivalent integer • e.g., “1234” (String) can be changed to 1234 (int) • Integer.parseInt() only works on Strings that only contain digits (and possibly a leading minus sign) WRAPPER CLASSES • Integer is a wrapper class • It provides a way to use primitive values in situations that require objects • Every primitive type has a matching wrapper class • Wrapper classes also provide general utility methods • parseInt() is an example of this • Double.parseDouble() is another example...
View Full Document

{[ snackBarMessage ]}

### Page1 / 9

05-random-numbers-and-parse - • To get a random double...

This preview shows document pages 1 - 9. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online