Monday, October 11, 2010

10. Random numbers

So our super-cool user input program is, well, super-cool but we want to make a game.  I mentioned making a where the user has to guess the number and you tell the user if the number is too high or too low.  We will also count the number of times they guess and print that out at the end.  However, if we want this game to be truly fun then we can't have the user guessing the same number over and over.  To solve this problem we are going to use random numbers!

To get the code for the random numbers (much like getting the code for the Scanner) you have to import it like so:
import java.util.Random;
So that's that and now to use the code.  In order to create a Random object you do this:
Random generator = new Random();
This creates a new Random object called generator where you can get random numbers from.  To get a random number from it you use this function:
generator.nextInt(10);
This will get a random number between 0 and 10.  So it gets an integer so to be able to use the number you have to assign it to an integer like so:
int r = generator.nextInt(10);
Now the integer r has a random number between 0 and 10!  Now, I have a challenge for you.  Try making the guessing number game I described above!  Don't worry, I'll have the code in the source code section and you can download it from there but try making your own and sending it to me at drenguinp@gmail.com or you can post it in the comments.

Hint:  Use  a while loop that goes while the user hasn't guessed correctly.  Also, use if loops to check if the user has guessed correctly or not. 

No comments:

Post a Comment