/* Lotto 對獎 */
import java.util.Arrays;
import java.util.Scanner;
public class LottoOnPrize {
final static int MAXNUM = 49; // 最大開獎號碼
public static void main(String[] args) {
final int totalBall = 7; // 總開獎號碼球數
int[] selectedNum = new int[totalBall]; // 選取的號碼
int[] openedNum = new int[totalBall]; // 開獎的號碼
int[] prizeNum = new int[totalBall]; // 中獎的號碼
// 號碼陣列初值化
initialArrayNum(selectedNum);
initialArrayNum(openedNum);
initialArrayNum(prizeNum);
// 取得輸入選取號碼
selectNum(selectedNum);
// 開獎
openNum(openedNum);
// 排序
Arrays.sort(openedNum);
Arrays.sort(selectedNum);
// 對獎
int onPrizeNum = onPrize(selectedNum, openedNum, prizeNum);
// 列印輸出
System.out.println();
System.out.println("開獎號碼是:");
printBallNum(openedNum);
System.out.println("你選取的號碼是:");
printBallNum(selectedNum);
if ( onPrizeNum > 0 ) {
System.out.println("恭喜您中了" + onPrizeNum + "個號碼獎.... !!! 中獎號碼是:");
printBallNum(prizeNum);
}
else
System.out.println("您摃....龜了 !!!");
}
// 號碼陣列初值化
private static void initialArrayNum(int[] a) {
for (int i=0; i<a.length; i++)
a[i] = 0;
}
// 產生號碼 (1-49)
private static int getNum(int maxNum) {
return (int) Math.floor(Math.random() * maxNum) + 1;
}
private static void printBallNum(int[] a) {
for (int i=0; i<a.length; i++) {
if ( a[i] != 0 )
System.out.print(a[i] + "\t");
}
System.out.print("\n");
}
// 對獎
private static int onPrize(int[] Selected, int[] Opened, int[] Prized) {
int count = 0;
for (int i=0; i<Selected.length; i++) {
for (int j=0; j<Opened.length; j++) {
if (Selected[i] == Opened[j]) {
Prized[count] = Selected[i];
count++;
break;
}
}
}
return count;
}
// 開獎
private static void openNum(int[] a) {
int times = 0; // 第幾次Counter
int inNum = 0;
while (times < a.length) {
inNum = getNum(MAXNUM);
if ( CheckBallNum(a, inNum) == 0 ) {
a[times] = inNum;
times = times + 1;
}
}
}
// 輸入選取號碼
private static void selectNum(int[] a) {
int times = 0; // 第幾次Counter
int inNum = 0; // 輸入號碼
Scanner scan = new Scanner(System.in);
while (times < a.length) {
System.out.print("請輸入你的第" + (times+1) + "個號碼:");
inNum = scan.nextInt();
if ( CheckNum(a, inNum) ) {
a[times] = inNum;
times++;
}
}
}
// 選取號碼檢查
private static boolean CheckNum(int[] a, int num) {
int returnStatus = CheckBallNum(a, num);
if (returnStatus == 1)
System.out.println("你選擇的號碼:" + num + " 不在 1 到 " + MAXNUM + " 範圍內 !!!");
else if (returnStatus == 2)
System.out.println("你選擇的號碼:" + num + " 重複了 !!!");
return (returnStatus == 0);
}
// 選取號碼檢查
private static int CheckBallNum(int[] a, int num) {
int result = 0;
if ((num < 1) || (num > MAXNUM))
result = 1;
else
{
for (int i = 0; i < a.length; i++) {
if (a[i] == num) {
result = 2;
break;
}
}
}
return result;
}
}
留言列表