This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "random Number" Watch "random Number" New topic

random Number

Divya Venkatesh

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
anbd this gives me a number like 1,2,3,4,5
I need to write a similar Function in JAVA
thanks in Advance

Dirk Schreckmann

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

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

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:
subject: random Number
It's not a secret anymore!