Android:Random生成随机数

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>

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值