Random number help

• 09-15-2008, 05:28 PM
jgonzalez14
Random number help
Hi all,

I need help with a random number feature. I want a random number between 1 and 26 (including 1 and 26). I have this

letter =(int) (Math.random() * 26 + 1);

Since Math.random() is 0 - .9999999, how do i get whole numbers?

should I do this:

so right now i am not getting accurate whole numbers. can anyone help?

Thanks
• 09-15-2008, 05:33 PM
Nicholas Jordan
Random has a nextInt() that takes an upper bound. There are short and well known ways to get the number in a range.
• 09-15-2008, 05:36 PM
jgonzalez14
I was looking into that but I have to keep the Random() function. Thanks tho. Is it possible to get some insight with the Random feature?
• 09-15-2008, 06:34 PM
Nicholas Jordan
basically simple
Well, in general what we do is int num = Math.random() times range plus floor. It is simple, you just have to do a timeout and think about it.

Some number times ( 0 - 1 ) gives, bascially, zero to the number. Then we often have a range so it is upper limit minus lower limit times random plus floor.
• 09-16-2008, 04:13 AM
```public class TestRandom {         /**         * @param args         */         public static void main(String[] args) {                 for (int i = 0; i < 50000; i++) {                         int letter = (int)(Math.random() * 26 + 1);                         System.out.println(letter);                         if(letter == 0 || letter > 26){                                 throw new RuntimeException("The value is out of range" + letter);                         }                 }         } }```
```    public static void main(String[] args) {         Random randomGenerator = new Random();                 for(int i = 0; i < 15; i++) {             int j = randomGenerator.nextInt(26);             System.out.println(j + 1);         }     }```