现在的位置: 首页 > 综合 > 正文

Android:Random生成随机数

2017年11月24日 ⁄ 综合 ⁄ 共 2517字 ⁄ 字号 评论关闭

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

cc.test;
 
import

java.util.HashSet;
import

java.util.Random;
import

android.app.Activity;
import

android.os.Bundle;
/**
 *
 *
Demo描述:
 *
Java中利用Random生成随机数
 *
 *
参考资料:
 *  
Thank you very much
 */
public

class

TestRandomActivity
extends

Activity {
    @Override
    public

void

onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        testRandom1();
        testRandom2();
        testRandom3();
    }
     
     
     
    //生成随机数
    private

void

testRandom1(){
        Random
random=
new

Random();
        for

(
int

i =
0;
i <
5;
i++) {
            System.out.println("random.nextInt()="+random.nextInt());
        }
        System.out.println("/////以上为testRandom1()的测试///////");
    }
     
     
     
    //在一定范围内生成随机数.
    //比如此处要求在[0
- n)内生成随机数.
    //注意:包含0不包含n
    private

void

testRandom2(){
        Random
random=
new

Random();
        for

(
int

i =
0;
i <
10;
i++) {
            System.out.println("random.nextInt()="+random.nextInt(20));
        }
        System.out.println("/////以上为testRandom2()的测试///////");
    }
     
     
    //在一定范围内生成不重复的随机数
    //在testRandom2中生成的随机数可能会重复.
    //在此处避免该问题
    private

void

testRandom3(){
        HashSet<integer>
integerHashSet=
new

HashSet<integer>();
        Random
random=
new

Random();
        for

(
int

i =
0;
i <
10;
i++) {
            int

randomInt=random.nextInt(
20);
            System.out.println("生成的randomInt="+randomInt);
            if

(!integerHashSet.contains(randomInt)) {
                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
version=
"1.0"

encoding=
"utf-8"?-->
<linearlayout
xmlns:android=
"http://schemas.android.com/apk/res/android"

android:layout_width=
"fill_parent"

android:layout_height=
"fill_parent"

android:orientation=
"vertical">
 
    <textview
android:layout_width=
"wrap_content"

android:layout_height=
"wrap_content"

android:text=
"Java中利用Random生成随机数"

android:layout_gravity=
"center"

android:layout_margintop=
"100dip">
 
</textview></linearlayout>

抱歉!评论已关闭.