[an error occurred while processing this directive] common/conf CSE 142 Lab Resources: Random

# University of Washington, CSE 142

## Lab Resources: Random

Except where otherwise noted, the contents of this document are Copyright 2013 Stuart Reges and Marty Stepp.

lab document created by Marty Stepp, Stuart Reges and Whitaker Brand

# Basic lab instructions

• Mouse over if you're not sure what they mean!
• Talk to your classmates for help.
• You may want to bring your textbook to future labs to look up syntax and examples.
• Stuck? Confused? Have a question? Ask a TA for help, or look at the book or past lecture slides.
• Complete as much of the lab as you can within the allotted time. You don't need to keep working on these exercises after you leave.
• Feel free to complete problems in any order.
• Make sure you've signed in on the sign-in sheet before you leave!

# `Random`

`Random`s allow us to generate random* numbers. Just like with Graphics, where we made one pen that we used to draw on the DrawingPanel, we make one Random object and use that to generate Random values throughout our program.
````import java.util.*;`
...

`Random randomName = new Random();`
```

*Technically pseudorandom, because it's surprisingly hard to generate truly random values, but theyre random enough for this class!

# `Random` syntax

Method name Description
`nextInt()` returns a random integer
`nextDouble()` returns a random real number in the range [0.0, 1.0).
`nextInt(max)` returns a random integer in the range [0, max). In other words, the number can be 0, (max - 1), or any integer between.
```   int x = randomName.nextInt(5); // x is 0, 1, 2, 3, or 4
double y = randomName.nextDouble();
```