Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

random Number

 
Divya Venkatesh
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
int number = (int)(Math.random() * 5) + 1;
Take a look at the J2SE API Documentation for an explanation of exactly what Math.random() returns.
 
Divya Venkatesh
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks so Much
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even simpler with java.util.Random:

Random = new Random();
int number = random.nextInt(5) + 1;
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic