Java第六次实验
抽奖程序:
import java.util.ArrayList; import java.util.Iterator; import java.util.Random; import java.util.Scanner; public class DrawPrize { private ArrayList<Integer> prize; private Random rand; private Scanner sc; public DrawPrize() { prize = new ArrayList<>(); rand = new Random(); sc = new Scanner(System.in); } public void addToSet() { System.out.println("总奖品数目为:"); int total = sc.nextInt(); while (prize.size() < total) { prize.add(rand.nextInt(1000)); } } public void drawPrize() { System.out.println("一、二、三等奖的个数分别为:"); int dp1 = sc.nextInt(); int dp2 = sc.nextInt(); int dp3 = sc.nextInt(); Iterator iterator = prize.iterator(); int i = 0; System.out.println("获得一等奖的是:"); while (i < dp1) { System.out.println(" " + iterator.next()); iterator.remove(); i++; } i = 0; System.out.println("获得二等奖的是:"); while (i < dp2) { System.out.println(" " + iterator.next()); iterator.remove(); i++; } i = 0; System.out.println("获得三等奖的是:"); while (i < dp3) { System.out.println(" " + iterator.next()); iterator.remove(); i++; } } public static void main(String[] args) { DrawPrize prizeLearning = new DrawPrize(); prizeLearning.addToSet(); prizeLearning.drawPrize(); } }
结果如下: