How to generate random numbers in Java

3 Answers

0 votes
package javaapplication1;
   
import java.util.Random;
   
public class Example {
    public static void main(String[] args) {
        Random rand = new Random(); 
        rand.setSeed(System.currentTimeMillis()); 

        int num;
        for (int i = 0; i < 30; i++) {   
            num = rand.nextInt() % 100; 
            System.out.println(num);
        }
    }
}
   
   
/*
run:
    
-6
-61
48
-84
7
80
-8
-51
-83
20
-95
18
46
-49
45
24
-81
94
-12
36
-84
-32
-36
91
61
39
-38
19
29
41
    
*/

 



answered Jan 21, 2016 by avibootz
edited Jan 21, 2016 by avibootz
0 votes
package javaapplication1;
   
import java.util.Random;
   
public class Example {
    public static void main(String[] args) {
        Random rand = new Random(); 
        rand.setSeed(System.currentTimeMillis()); 

        int num;
        for (int i = 0; i < 30; i++) {   
            num = rand.nextInt() % 100; 
            System.out.println(Math.abs(num));
        }
    }
}
   
   
/*
run:
    
48
71
75
86
58
28
98
44
74
16
21
16
3
3
98
77
87
5
24
82
9
16
19
67
38
59
36
74
5
23
    
*/

 



answered Jan 21, 2016 by avibootz
0 votes
package javaapplication1;
   
import java.util.Random;
   
public class Example {
    public static void main(String[] args) {
        Random rand = new Random(); 
        rand.setSeed(System.currentTimeMillis()); 

        int num;
        for (int i = 0; i < 30; i++) {   
            num = rand.nextInt(100); 
            System.out.println(num);
        }
    }
}
   
   
/*
run:
    
68
76
80
29
33
2
26
59
7
6
62
29
39
59
65
26
61
36
54
18
70
96
75
27
52
0
24
49
32
28
    
*/

 



answered Jan 21, 2016 by avibootz

Related questions

1 answer 108 views
1 answer 117 views
1 answer 137 views
1 answer 121 views
1 answer 158 views
1 answer 196 views
...