next up previous
Next: HashMaps Up: The Frightened Freshers Guide Previous: The Java API

java.util.Random

Say you wanted to add some randomness into your application, how would you do it? Well, by using the java.util.Random package! First of all, you will need to import the package into your project.
\begin{lstlisting}
import java.util.Random;
\end{lstlisting}

This tells java that when its compiling it should include the code from the package java.util.Random into it. If you dont include this and try and write code with Random bits in, then it actually wont compile. Looking back at the Java API for Random, you can see that its constructor has no parameters (Or a seed with datatype long). So to create a nice Random object from which you can spawn Random numbers you can do the following.
\begin{lstlisting}
Random itsARandomThing = new Random();
\end{lstlisting}

You can see quite clearly now that Random is an object (It uses the new keyword). To get random numbers out of this thing you just spawned you can use the method nextInt. As with when calling things not in the Class you are in now, the dot notation must be used.


\begin{lstlisting}
int someRandomNumber = itsARandomThing.nextInt(6);
\end{lstlisting}

The parameter in brackets, if you read the API, is the upper limit value that the Random object can generate for you. So this would be almost perfect for a dice although the Random starts at 0 and ends at whatever is given in brackets. Easy enough to fix:
\begin{lstlisting}
int someRandomNumber = 1 + (itsARandomThing.nextInt(5));
\end{lstlisting}
This way you can be sure that the value you will get back in someRandomNumber is between 1 and 6.

Random also generates other random things, if you check the API you will see that there are methods for getting Booleans, Doubles, Integers and other things out.


next up previous
Next: HashMaps Up: The Frightened Freshers Guide Previous: The Java API
Tom Carlson 2006-01-10