MainActivity如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
package
import
import
import
import
/** * * * * * * */ public
extends
@Override public
super .onCreate(savedInstanceState); setContentView(R.layout.main); testRandom1(); testRandom2(); testRandom3(); } //生成随机数 private
Random new
for
int
0 ; 5 ; System.out.println( "random.nextInt()=" +random.nextInt()); } System.out.println( "/////以上为testRandom1()的测试///////" ); } //在一定范围内生成随机数. //比如此处要求在[0 //注意:包含0不包含n private
Random new
for
int
0 ; 10 ; System.out.println( "random.nextInt()=" +random.nextInt( 20 )); } System.out.println( "/////以上为testRandom2()的测试///////" ); } //在一定范围内生成不重复的随机数 //在testRandom2中生成的随机数可能会重复. //在此处避免该问题 private
HashSet<integer> new
Random new
for
int
0 ; 10 ; int
20 ); System.out.println( "生成的randomInt=" +randomInt); if
integerHashSet.add(randomInt); System.out.println( "添加进HashSet的randomInt=" +randomInt); } else
System.out.println( "该数字已经被添加,不能重复添加" ); } } System.out.println( "/////以上为testRandom3()的测试///////" ); } }</integer></integer> |
main.xml如下:
1
2
3
4
5
6
|
<!--?xml "1.0"
"utf-8" ?--> <linearlayout "http://schemas.android.com/apk/res/android"
"fill_parent"
"fill_parent"
"vertical" > <textview "wrap_content"
"wrap_content"
"Java中利用Random生成随机数"
"center"
"100dip" > </textview></linearlayout>
|