1 package 随机数;
2
3 import java.util.Random;
4
5 public class 彩票抽奖 {
6
7 public static void main(String[] args) {
8 // TODO 自动生成的方法存根
9
10
11 //彩票抽奖。在1~36之间随机7个数,且不能重复。1定义数组2实例化随机数3生成随机序列4对产生的数验证5去0;6去重复7输出
12
13
14 int[] cp = new int[7];//定义一个数组,长度是7
15 Random dom = new Random();//先实例化随机变量
16 System.out.println("抽到的彩票号码是:");
17 for(int i=0; i<cp.length; i++)
18 {
19 int t = dom.nextInt(36);//定义随机数的取值范围,接收随机数
20
21
22
23 //对产生的数字进行验证.如果出现0,那么要重新生成一个数。
24 //只要出现0就continue,继续生成一个数,直到没有0出现。
25 if(t==0) //
26 {
27 i--; //
28 continue;//
29 }
30
31
32
33 //验证完成后,去重复。检查重新生成的数是否与其他数重复
34 else
35 {
36 boolean h = false;//定义h
37 for(int c:cp)//遍历。使每一个数都和他前面的所有数挨个比较
38 {
39 if(c==t)//,如果有重复就执行下面语句。不重复就返回for。
40 {
41 i--;
42 h = true;
43 break;//break中断,只要出现重复数字就返回,不必在和后面的数比较了。
44 }
45 }
46
47 if(h)
48 {
49 continue;//
50
51 }
52 }
53
54 cp[i]=t;
55
56 }
57
58 for(int c:cp) //遍历数组输出
59 {
60 System.out.print(c+" ");
61 }
62
63 System.out.println("\n");
64
65
66
67
68
69 //生成验证码
70 String ran1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";//定义字符串
71 int number = ran1.length();//ran1的长度
72 Random ran = new Random();//实例化随机数
73 System.out.print("生成验证码:");
74 for(int i=0; i<4; i++)
75 {
76 int a = ran.nextInt(number-1);//从61中随机取数
77 String a1 = ran1.substring(a, a+1);//截取第a+1个字符
78 System.out.print(a1);
79 }
80
81
82
83 }
84
85 }