编写程序实现体彩大乐透机选5注
题目
编写程序实现体彩大乐透机选五注,把机选结果打印在控制台上,具体规则如下
- 大乐透由前区和后区构成
- 前区:从1-35中随机选出不重复的5个数
- 后区:从1-12中随机选出不重复的2个数
Set集合实现就不用考虑重复的问题,不像1.0LinkedList集合就需要考虑是否重复,还要去重。而Set可以存储唯一、无序的对象。
创建Set集合对象
//集合类型为Int
Set<Integer> list = new HashSet<Integer>();
给集合添加数据
Set<Integer> list = new HashSet<Integer>();
while (list.size() != count) {
// 范围(max-min+1)+1list.add(rand.nextInt(max - min + 1) + 1);
}
Integer[] array = new Integer[list.size()];
//转成数组
list.toArray(array);
for (int i = 0; i < array.length; i++) {System.out.print(array[i]+" ");
}
// System.out.print(list);
完整代码
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Random;
import java.util.Set;public class CaiPiao2 {static Random rand = new Random();public static void main(String[] args) {int sum =0;do {System.out.print("第"+(sum+1)+"注彩票为:");listAdd(1, 35, 5);listAdd(1,12,2);System.out.println();sum++;}while(sum<5);}//定义方法,最大值,最小值,一次取出多少个数 private static void listAdd(int min, int max, int count) {Set<Integer> list = new HashSet<Integer>();while (list.size() != count) {// 范围(max-min+1)+1list.add(rand.nextInt(max - min + 1) + 1);}Integer[] array = new Integer[list.size()];//转成数组list.toArray(array);for (int i = 0; i < array.length; i++) {System.out.print(array[i]+" ");}
// System.out.print(list);}
}