package demo2; import java.util.Arrays; import java.util.Random; /** * 系統作為彩票雙色球生成器,模擬機選一注雙色球的彩票號碼: * 1、需要從“01”到“32”中隨機選擇出6個數字作為紅色球且這6個數字不能重復; * 2、並從”01”到”07”中隨機選擇一個數字作為藍色球; * 3、7個數字合到一起作為一注雙色球彩票的號碼; */ public class DoubleBall { public static void main(String[] args) { String[] RED_BALLS = { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32" }; String[] BLUE_BALLS = { "01", "02", "03", "04", "05", "06", "07" }; boolean[] redFlags = new boolean[RED_BALLS.length]; String[] redBalls = new String[6]; String blueBall; Random ran = new Random(); // red for (int i = 0; i < redBalls.length; i++) { int index; do { index = ran.nextInt(RED_BALLS.length); } while (redFlags[index]); /** * redFlags[index]用途: * 當redFlags[index]=true表示已經重復,所以你需要 * 再執行do當中的代碼重新獲取index */ redBalls[i] = RED_BALLS[index]; redFlags[index] = true; } // blue blueBall = BLUE_BALLS[ran.nextInt(BLUE_BALLS.length)]; Arrays.sort(redBalls); System.out.println("**********本期開獎**********"); System.out.println("紅球: "); for (int i = 0; i < redBalls.length; i++) { System.out.print("(" + redBalls[i] + ") "); } System.out.println(); System.out.println("籃球: "); System.out.print("(" + blueBall + ") "); } }