aspose file tools*
The moose likes Beginning Java and the fly likes random Number Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "random Number" Watch "random Number" New topic
Author

random Number

Divya Venkatesh
Greenhorn

Joined: Nov 05, 2002
Posts: 28
can anyone tell me how to generate a random number between 1 to 5.
I am new tojava programming and i know in c it works like
random1=(rand()%5)+1;
anbd this gives me a number like 1,2,3,4,5
I need to write a similar Function in JAVA
thanks in Advance


Divya
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
int number = (int)(Math.random() * 5) + 1;
Take a look at the J2SE API Documentation for an explanation of exactly what Math.random() returns.


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Divya Venkatesh
Greenhorn

Joined: Nov 05, 2002
Posts: 28
Thanks so Much
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Even simpler with java.util.Random:

Random = new Random();
int number = random.nextInt(5) + 1;


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: random Number