1import java.util.Random;
2
3Random rand = new Random();
4
5// Obtain a number between [0 - 49].
6int n = rand.nextInt(50);
7
8// Add 1 to the result to get a number from the required range
9// (i.e., [1 - 50]).
10n += 1;
1import java.util.Random;
2
3Random rand = new Random();
4int maxNumber = 10;
5
6int randomNumber = rand.nextInt(maxNumber) + 1;
7
8System.out.println(randomNumber);
1import java.util.Random;
2
3class scratch{
4 public static void main(String[] args) {
5 Random rand = new Random();
6 System.out.println( rand.nextInt(5) );
7 //prints a random Int between 0 - 4 (including 0 & 4);
8 }
9}
1import java.lang.Math;
2
3int randomNumber;
4
5int minimum = 1;
6int maximum = 10 - minimum;
7
8randomNumber = (int)((Math.random()*maximum) + minimum);
9
10System.out.println("Random Number (Between 1-10): " + randomNumber);
1// java.util.random example
2import java.util.Random;
3public class JavaRandomClass
4{
5 public static void main(String[] args)
6 {
7 Random random = new Random();
8 // random integers in range 0 to 999
9 int randInt1 = random.nextInt(1000);
10 int randInt2 = random.nextInt(1000);
11 // printing random integers
12 System.out.println("Random Integers: " + randInt1);
13 System.out.println("Random Integers: " + randInt2);
14 // here we are generating Random doubles
15 double randDou1 = random.nextDouble();
16 double randDou2 = random.nextDouble();
17 // printing random doubles
18 System.out.println("Random Doubles: " + randDou1);
19 System.out.println("Random Doubles: " + randDou2);
20 }
21}
1import java.util.Random;
2class GenerateRandom {
3 public static void main( String args[] ) {
4 Random rand = new Random(); //instance of random class
5 int upperbound = 25;
6 //generate random values from 0-24
7 int int_random = rand.nextInt(upperbound);
8 double double_random=rand.nextDouble();
9 float float_random=rand.nextFloat();
10
11 System.out.println("Random integer value from 0 to" + (upperbound-1) + " : "+ int_random);
12 System.out.println("Random float value between 0.0 and 1.0 : "+float_random);
13 System.out.println("Random double value between 0.0 and 1.0 : "+double_random);
14 }
15}