How to generate random integers in a specific range in Java

3 Answers

0 votes
package javaapplication1;

public class JavaApplication1 {

    public static void main(String[] args) {
     
        int min = 3, max = 13, n;
        
        for (int i = 0; i < 20; i++) {
                n = min + (int)(Math.random() * ((max - min) + 1));
                System.out.print(n + " ");
            }
        }
    }
 
/*

run:

3 3 12 10 9 6 13 8 9 5 7 12 7 12 3 13 7 9 13 9

*/

 



answered Oct 8, 2016 by avibootz
0 votes
package javaapplication1;

import java.util.Random;

public class JavaApplication1 {

    public static void main(String[] args) {
     
        int min = 3, max = 13, n;
        
        int range = max - min + 1;
        Random random = new Random();
        
        for (int i = 0; i < 20; i++) {
                n = (int) (range * random.nextDouble()) + min;
                System.out.print(n + " ");
            }
        }
    }
 
/*

run:

4 10 7 3 10 9 3 10 10 6 5 9 6 10 5 11 11 12 10 11

*/

 



answered Oct 8, 2016 by avibootz
0 votes
package javaapplication1;

import java.util.concurrent.ThreadLocalRandom;

public class JavaApplication1 {

    public static void main(String[] args) {
     
        int min = 3, max = 13, n;
        
        for (int i = 0; i < 20; i++) {
                n = ThreadLocalRandom.current().nextInt(min, max + 1);
                System.out.print(n + " ");
            }
        }
    }
 
/*

run:

12 13 11 9 11 13 11 4 6 6 10 7 3 9 9 9 10 4 7 5

*/

 



answered Oct 8, 2016 by avibootz

Related questions

5 answers 245 views
1 answer 139 views
2 answers 192 views
2 answers 132 views
1 answer 93 views
1 answer 155 views
...