0

I was able to generate a random number between [0,50] in my java code but how do I proceed in order to create for example a number in the range of [1,49]

This is my code:

public class Totoloto 
{
    public static void main(String[] args) 
    {
        int n = (int) (Math.random()*50);
        System.out.println("Number generated: "+n); 
    }    
}
jww
  • 97,681
  • 90
  • 411
  • 885
Gazelle
  • 53
  • 1
  • 3
  • 11

4 Answers4

3

To get a random number from 1-49, you should pick a random number between 0-48, then add 1:

int min=1;
int max=49;

Random random=new Random();
int randomnumber=random.nextInt(max-min)+min;
Barett
  • 5,826
  • 6
  • 51
  • 55
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37
2

Make use of the Random class. If you have a method designed as generateRandom(int min, int max) then you could create it like this

private static Random r = new Random();

public static void main(String[] args) {
    for(int i = 0;i<10; ++i)
        System.out.println(generateRandom(-1,1));
}


private static int generateRandom(int min, int max) {
    // max - min + 1 will create a number in the range of min and max, including max. If you don´t want to include it, just delete the +1.
    // adding min to it will finally create the number in the range between min and max
    return r.nextInt(max-min+1) + min;
}
SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
  • 1
    This is actually not optimized as you initialize a new `Random` each invocation. – Mena Oct 07 '15 at 14:09
  • Does it really a bad to create new Random in each invocation!! Won't GC automatically delete the Random object once it returns to the called method!!! – ValarDohaeris Oct 07 '15 at 14:12
1

You can use a slightly different idiom of randomization:

Random r = new Random();
while (true) {
    // lower bound is 0 inclusive, upper bound is 49 exclusive
    // so we add 1
    int n = r.nextInt(49) + 1;
    System.out.println("Number generated: "+n); 
}

Will print an infinite list of random numbers between 1 and 49.

Equivalent Java 8 idiom:

r.ints(0, 49).forEach((i) -> {System.out.println(i + 1);});
Mena
  • 47,782
  • 11
  • 87
  • 106
  • but how does this line work? int n= r.nextInt(50) +1; By adding 1 how can that convert the range into [1,49]? – Gazelle Oct 07 '15 at 14:06
  • @Gazelle typo my side, it's 49 - fixed. Now the upper bound is 49, so the random `int` is between 0 and 48 inclusive. You add 1 all times, so it's between 1 and 49 inclusive. – Mena Oct 07 '15 at 14:07
0

Try using the Random class from the util package:

Random r = new Random();
int n = r.nextInt(49) + 1;
hsotweelvl
  • 85
  • 5