Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

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 285 views
1 answer 169 views
2 answers 218 views
2 answers 158 views
1 answer 111 views
1 answer 186 views
...