How to generate random number between min and max in Java

3 Answers

0 votes
import java.util.concurrent.ThreadLocalRandom;
 
public class MyClass {
    public static void main(String args[]) {
        int min = 17;
        int max = 31;
        int number = ThreadLocalRandom.current().nextInt(min, max + 1);
 
        System.out.println(number);
    }
}
 
 
 
/*
run:
 
25
 
*/

 



answered Mar 22, 2021 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        int min = 17;
        int max = 31;
        int number =  min + (int)(Math.random() * ((max - min) + 1));
 
        System.out.println(number);
    }
}
 
 
 
/*
run:
 
29
 
*/

 



answered Mar 22, 2021 by avibootz
0 votes
import java.util.Random;

public class MyClass {
    public static void main(String args[]) {
        Random random = new Random();
        
        int min = 17;
        int max = 31;
        int number =  random.nextInt(max + 1 - min) + min;
 
        System.out.println(number);
    }
}
 
 
 
/*
run:
 
17
 
*/

 



answered Mar 22, 2021 by avibootz

Related questions

1 answer 199 views
2 answers 241 views
1 answer 114 views
1 answer 113 views
1 answer 115 views
1 answer 110 views
...