此次的作业是做一个抽奖程序,要求可以设定参与抽奖的总人数和奖项的个数,获奖不可重复。
方法一:
package draw;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Draw {
public ArrayList<Integer> list;
public Draw(){
list = new ArrayList<Integer>();
}
public void deal(int num){
//向容器添加奖券(使用循环)
for(int i = 0;i < num;i++){
list.add(i);
}
//打乱顺序
Collections.shuffle(list);
}
public void drawLottery(int n){
//产生n各指定范围(0~list.size)的随机数
Random rd = new Random();
for(int i = 0;i < n;i++){
int index = rd.nextInt(list.size());
/*
* 获得容器中以产生的随机数为下标的元素的内容
* 即为获奖的奖券的抽奖号,输出
*/
System.out.print(list.get(index)+" ");
//将已获奖的元素(奖券)从容器中删除
list.remove(index);
}
System.out.println();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Draw dr = new Draw();
dr.deal(1000);
System.out.println("-----一等奖-----");
dr.drawLottery(1);
System.out.println("-----二等奖-----");
dr.drawLottery(3);
System.out.println("-----三等奖-----");
dr.drawLottery(4);
}
}
方法二:
package homework;
import java.util.*;
public class choujiang {
private HashSet<Integer> set;
private Random rand;
private Scanner sc;
public choujiang() {
set = new HashSet<>();
rand = new Random();
sc = new Scanner(System.in);
}
public void addToSet() {
System.out.println("请输入总奖品数: ");
int total = sc.nextInt();//total prize number
while (set.size() < total) {
set.add(rand.nextInt(1000)); //设置总共有多少个获奖
}
}
public void drawPrize() {
System.out.println("分别按顺序输入一二三等奖的获奖总数:");
//分别设置每等奖的获奖人数
int prize1 = sc.nextInt();//first prize number
int prize2 = sc.nextInt();
int prize3 = sc.nextInt();
Iterator iterator = set.iterator();
int i = 0;
System.out.println("获得一等奖的号码是 : ");
while (i < prize1) {
System.out.println(iterator.next());
iterator.remove();
i++;
}
i = 0;
System.out.println("获得二等奖的号码是 :");
while (i < prize2) {
System.out.println(iterator.next());
iterator.remove();
i++;
}
i = 0;
System.out.println("获得三等奖的号码是 :");
while (i < prize3) {
System.out.println(iterator.next());
iterator.remove();
i++;
}
}
public static void main(String[] args) {
choujiang setLearning = new choujiang();
setLearning.addToSet();
setLearning.drawPrize();
}
}