상속 / Collection / Random() / Scanner
import java.util.*;
class MyNums {
private Integer[] nums;
public MyNums() {
nums = autoSelect(6);
}
public MyNums(Integer... nums) {
Arrays.sort(nums);
this.nums = nums;
}
protected Integer[] autoSelect(int count) {
Random r = new Random();
HashSet<Integer> set = new HashSet<Integer>();
while(set.size() < count) {
set.add(r.nextInt(45) + 1);
}
Integer[] nums = set.toArray(new Integer[0]);
Arrays.sort(nums, 0, 6);
return nums;
}
@Override
public String toString() {
return Arrays.toString(nums);
}
public Integer[] getNums() {
return nums;
}
public void setNums(Integer...nums) {
this.nums = nums;
}
}
class LottoNums extends MyNums {
public static final int BONUS = 6;
public LottoNums() {
setNums(autoSelect(7));
}
public LottoNums(Integer...nums) {
super(nums);
}
public Integer getBonusNum() {
return getNums()[BONUS];
}
@Override
public String toString() {
return super.toString() + "\n*마지막 번호가 보너스 번호입니다.";
}
}
class LottoProgram {
private Scanner sc;
private MyNums[] nums;
private LottoNums goal;
private int[] count = new int[5];
public LottoProgram() {
sc = new Scanner(System.in);
howManyPlay();
getGoal();
showResult();
}
private void howManyPlay() {
System.out.print("몇개를 살까요? : ");
int count = sc.nextInt();
nums = new MyNums[count];
for(int idx = 0; idx < count; idx++) {
nums[idx] = new MyNums();
}
}
private void getGoal() {
goal = new LottoNums();
System.out.println("당첨번호를 추첨 합니다.");
System.out.println("당첨번호 : " + goal);
}
private void addCount(int rank) {
int idx = rank - 1;
int num = count[idx];
num++;
count[idx] = num;
}
private void showResult() {
Integer[] excBonus = Arrays.copyOfRange(
goal.getNums(), 0, LottoNums.BONUS
);
List<Integer> goalList = new ArrayList<>(
Arrays.asList(excBonus)
);
int no = 1;
for(MyNums temp : nums) {
List<Integer> myList =
new Vector<Integer>(Arrays.asList(temp.getNums()));
myList.retainAll(goalList);
int count = myList.size();
int rank = 0;
switch (count) {
case 6 :
rank = 1;
System.out.println(myList);
break;
case 5 :
int indexOfBonus = Arrays.binarySearch(
temp.getNums(), goal.getBonusNum()
);
if(indexOfBonus >= 0) {
rank = 2;
} else {
rank = 3;
}
break;
case 4 :
rank = 4;
break;
case 3 :
rank = 5;
break;
}
String result;
if(rank == 0) {
result = "꽝";
} else {
addCount(rank);
result = rank + "등";
}
System.out.println((no) + ": 회 게임 결과");
System.out.println("\t일치번호 -> " + myList);
no++;
}
System.out.println((no - 1) + ": 회 게임 결과\n");
for(int i = 0; i < count.length; i++) {
System.out.println((i + 1) + "등 당첨횟수 : " + count[i]);
}
}
}
public class LottoGame {
public static void main(String[] args) {
new LottoProgram();
}
}