How to generate random integers between specific range in Java

5 Answers

0 votes
import java.util.Random;
 
public class MyClass
{
    public static int generateRandomInteger(int min, int max) {
        return new Random().nextInt(max - min + 1) + min;
    }
    
    public static void main(String[] args)
    {
        int min = 4, max = 11;
 
        for (int i = 0; i < 10; i++) {
            System.out.println(generateRandomInteger(min, max));
        }
    }
}





/*
run:

10
8
6
5
9
11
7
11
4
8

*/

 



answered Mar 18, 2023 by avibootz
0 votes
import java.util.Random;
 
public class MyClass
{
    public static int generateRandomInteger(int min, int max) {
        Random rand = new Random();
 
        return rand.ints(min, (max + 1))    
                    .findFirst()            
                    .getAsInt();            
    }
    
    public static void main(String[] args)
    {
        int min = 4, max = 11;
 
        for (int i = 0; i < 10; i++) {
            System.out.println(generateRandomInteger(min, max));
        }
    }
}





/*
run:

10
8
9
8
8
6
4
5
11
9

*/

 



answered Mar 18, 2023 by avibootz
0 votes
import java.util.Random;
  
public class MyClass
{
    public static int generateRandomInteger(int min, int max) {
        return min + (int)(Math.random() * ((max - min) + 1));
    }
     
    public static void main(String[] args)
    {
        int min = 4, max = 11;
  
        for (int i = 0; i < 10; i++) {
            System.out.println(generateRandomInteger(min, max));
        }
    }
}
 
 
 
 
 
/*
run:
 
8
9
11
11
6
7
10
4
4
11
 
*/

 



answered Mar 18, 2023 by avibootz
0 votes
import java.util.concurrent.ThreadLocalRandom;
  
public class MyClass
{
    public static int generateRandomInteger(int min, int max) {
        return ThreadLocalRandom.current().nextInt(min, max + 1);
    }
     
    public static void main(String[] args)
    {
        int min = 4, max = 11;
  
        for (int i = 0; i < 10; i++) {
            System.out.println(generateRandomInteger(min, max));
        }
    }
}
 
 
 
 
 
/*
run:
 
6
11
4
8
4
8
6
7
5
11
 
*/

 



answered Mar 18, 2023 by avibootz
0 votes
import java.security.SecureRandom;
  
public class MyClass
{
    public static int generateRandomInteger(int min, int max) {
        SecureRandom random = new SecureRandom();
        random.setSeed(random.generateSeed(20)); // 20 bytes
 
        return random.nextInt((max - min) + 1) + min;
    }
     
    public static void main(String[] args)
    {
        int min = 4, max = 11;
  
        for (int i = 0; i < 10; i++) {
            System.out.println(generateRandomInteger(min, max));
        }
    }
}
 
 
 
 
 
/*
run:
 
8
5
11
5
6
6
8
6
4
10
 
*/

 



answered Mar 18, 2023 by avibootz

Related questions

3 answers 237 views
1 answer 138 views
2 answers 192 views
2 answers 131 views
1 answer 92 views
1 answer 154 views
...