- import java.util.Random;
- public class RandomDemo {
- public static void main(String[] args) {
- lottery();
- }
- /**
- * 此方法判断是否存在重复内容
- *
- * @param temp
- * 指的是已保存的数据
- * @param num
- * 指的是新生成的数据
- * @return 如果存在返回 false, 不存在返回 true(逻辑别扭)
- */
- public static boolean isRepeat(int[] temp, int num) {
- for (int x = 0; x < temp.length; x++) {
- if (num == temp[x]) {
- return false;
- }
- }
- return true;
- }
- public static void lottery() {
- // 随机摇号
- Random rand = new Random();
- int[] data = new int[7];// 开辟一个 7 个元素的数组
- int foot = 0; // 此数组的脚标
- while (foot < 7) {
- // 不知道循环多少次可以保存完数据, while 循环
- int t = rand.nextInt(36) + 1;// 生成随机数 [1,37)
- if (isRepeat(data, t)) {
- // 返回的不重复数据
- data[foot++] = t; // 保存
- }
- }
- java.util.Arrays.sort(data); // 排序
- for (int lottery : data) {
- System.out.print(lottery + " ");
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2961021.html