【代码】双色球摇号程序

前言

通过输入摇号次数,摇出每次前区和后区的数据,前区6个1~33的数据,后区1个1~16的数据,每个区内的所有数据不重复

源代码

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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package io.github.feiju12138;
/**
* 双色球摇号程序
*/

import java.util.Random;
import java.util.Scanner;

public class Lottery {

// 分别创建前区和后区的成员变量
public static int[] before = new int[6];
public static int after = 0;

// 执行摇号方法
public static void start() {

// 创建随机数对象
Random r = new Random();

// 初始化序号
int index = 0;

// 无限循环
while(true) {

// 生成1~33的随机数
int num = r.nextInt(33)+1;

/*
检查生成的随机数是否与已存入数据重复
如果重复,再次生成新的随机数
如果不重复则将随机数存入到序号为i的数组中,同时序号自增
*/
if(!check(num)) {
before[index] = num;
index++;
}

// 当成功存入数据6次,跳出无限循环
if(index==6) {
break;
}

}

// 生成1~16的随机数
after = r.nextInt(16)+1;

// 将所有生成的不重复随机数打印输出
System.out.println("本次双色球摇号为:");
System.out.print("前区");
for(int i = 0; i < before.length; i++) {
System.out.print(" "+before[i]);
}
System.out.println();
System.out.println("后区 "+after);

}

// 检查重复方法
public static boolean check(int num) {

// 创建一个键,默认为false
boolean key = false;

// 循环遍历before数组
for(int i = 0; i < before.length; i++) {

// 如果传入的数据与before已存入数据相同,键为true
if(num==before[i]) {
key = true;
}

}

// 返回键
return key;

}

// 主方法
public static void main(String[] args) {

// 手动输入摇号次数
Scanner sc = new Scanner(System.in);
System.out.print("请输入摇号次数:");
int num = sc.nextInt();

// 打印每一次摇号结果
Lottery lottery = new Lottery();
for(int i = 0; i < num; i++) {
lottery.start();
}

}

}

完成