Skip to content

Instantly share code, notes, and snippets.

@zhyunk
Last active March 3, 2023 15:59
Show Gist options
  • Save zhyunk/cbcc4e13d53bb1de744c39ab0e00d874 to your computer and use it in GitHub Desktop.
Save zhyunk/cbcc4e13d53bb1de744c39ab0e00d874 to your computer and use it in GitHub Desktop.
과제 7. 로또 당첨 프로그램
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
/*
* 과제 7. 로또 당첨 프로그램
*
* 작성자 : 김지현
* 작성일 : 2023-03-03
* */
public class MiniAssignment07 {
public static void main(String[] args) {
MyScanner my = new MyScanner();
int cnt = 0;
char chNo = 'A';
int[][] arrAllMyLotto = null;
System.out.println("[로또 당첨 프로그램]");
System.out.println();
// 1. 로또 구매 개수 입력
cnt = my.getScannerReturnIntRange("로또 개수를 입력해주세요.(숫자 1 ~ 10):", 1, 10);
my.close();
// 2. 입력한 개수만큼의 로또 개수 생성 후 출력
arrAllMyLotto = new int[cnt][6];
for (int i = 0; i < cnt; i++) {
arrAllMyLotto[i] = getMakeLottoNumbers();
}
chNo = 'A';
for (int[] arr: arrAllMyLotto) {
System.out.print(String.format("%c\t", chNo++));
printLottoNumbers(arr);
System.out.println();
}
// 3. 로또 당첨번호 생성 후 출력
int[] arrDangChumNumbers = getMakeLottoNumbers();
System.out.println("\n[로또 발표]");
System.out.print("\t");
printLottoNumbers(arrDangChumNumbers);
// 4. 당첨번호와 구매 로또 비교하여 숫자 일치여부 판단
chNo = 'A';
System.out.println("\n\n[내 로또 결과]");
int sameNumCnt = 0;
for (int[] arr: arrAllMyLotto) {
System.out.print(String.format("%c\t", chNo++));
printLottoNumbers(arr);
// 당첨 숫자 확인
for (int j = 0; j < arr.length; j++) {
for (int k = 0; k < arrDangChumNumbers.length; k++) {
if (arrDangChumNumbers[k] == arr[j]) {
sameNumCnt++;
break;
}
}
}
System.out.println(String.format(" => %d개 일치", sameNumCnt));
sameNumCnt = 0;
}
}
public static void printLottoNumbers(int[] arr) {
for (int j = 0; j < arr.length; j++) {
System.out.print(String.format("%02d", arr[j]));
if (j < arr.length - 1) {
System.out.print(",");
}
}
}
public static int[] getMakeLottoNumbers() {
int[] arrLotto = new int[6];
Random rd = new Random();
int temp = -1;
boolean isSame = false;
for (int i = 0; i < 6; i++) {
temp = (rd.nextInt(45) + 1);
// 중복 검사
for (int j = 0; j < i; j++) {
if (arrLotto[j] == temp) {
isSame = true;
i--;
break;
}
}
if (!isSame) arrLotto[i] = temp;
isSame = false;
}
Arrays.sort(arrLotto);
return arrLotto;
}
static class MyScanner {
String str;
Scanner scan;
MyScanner() {
scan = new Scanner(System.in);
}
public int getScannerReturnIntRange(String text, int min, int max) {
// min = 최소(포함) 범위 , max = 최대(포함) 범위
str = "";
while (true) {
System.out.print(text);
str = scan.nextLine();
if (!str.replaceAll(" ", "").isEmpty() && str.replaceAll("[0-9]", "").isEmpty()) {
if (Integer.parseInt(str) < max + 1 && Integer.parseInt(str) > min - 1)
break;
}
}
return Integer.parseInt(str);
}
public void close() {
scan.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment