Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Random number

 
King-Chieh Wang
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear All,
How do I create a random number range inbetween [5,10]?
thanks for answering!!
Jack
 
Sanyev Babu
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The code above uses the random methord in the java.lang.Math class it generates a double random number between 0 and 1 including 0 and excluding 1. You can multiply the number with 5 and then add 5 to it to obtain a randum number between 5 and 10. Note that the number generated will be a double number if you want it to be int you must down cast it.
 
Sanyev Babu
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry the code
public void amethord()
{ System.out.println("amethord");
}
in my above post is not needed. I was working with some other example which needed that methord. I modified that file to make the example. Sorry for that.
 
Vicken Karaoghlanian
Ranch Hand
Posts: 522
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sanyev-
In regards to your second post, you can always edit your first post instead of creating a new one.
King-Chiehm-
Although the solutions posted by Sanyev is correct however it is not accurate because the number 10 will never be reached, the closest number you'll get is 9.9999999.
So technically speaking, [5,10) will describe the answer more accurately.
[ March 09, 2004: Message edited by: Vicken Karaoghlanian ]
 
Carlos Failde
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
java.util.Random random = new java.util.Random();
int n = 5 + random.nextInt(6);
nextInt(6) returns numbers between 0 inclusive and 6 exclusive
 
Sanyev Babu
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The above code will generate integer random numbers in the interval [5,10] both inclusive. Note that the random number in the interval [0,1) is multipled with 6 so we will get numbers in the range [0,6). Adding five to the value will bring the value to [5,11). As the result is a double value casting it to an int will bring the value to [5,10] since casting to int will truncate the decimal value rather than round the number.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic