수행 목적 : Scanner의 입력함수와 조건문 및 반복문과 배열을 통한 로또 당첨 로직 작성
간략 소개 : 로또는 1-45개의 숫자 사이의 값중 6개를 맞추면 당첨되는 복권입니다. 로또의 개수를 구매하고(구매수량 입력), 당첨번호를 생성한다. 이후, 구매한 로또의 당첨번호를 판단하는 프로그램을 작성해 보세요.
필수 준수사항
- 로또 구매 수량 입력
- 입력한 개수만큼의 로또 개수 생성
- 로또 당첨 번호 생성(숫자값은 중복 배제 및 정렬해서 표시)
- 당첨 번호와 구매 로또 비교하여 숫자 일치 여부 판단
- Collections.shuffle 함수 사용 금지! (shuffle함수는 과제의 취지와 맞지 않기 때문에, 사용시 0점 처리)
import java.util.*;
/**
* 로또 당첨 프로그램
*/
public class LottoNumberGenerator {
/**
* 로또 번호 생성
*
* @return 로또 번호 배열
*/
public static int[] lottoGenerator() {
int[] lotto = new int[6];
Random random = new Random();
for (int i = 0; i < lotto.length; i++) {
// 1 ~ 45 사이의 랜덤한 수 생성 후 배열에 담기
lotto[i] = random.nextInt(45) + 1;
// 기존에 배열에 담겨 있는 수와 새롭게 담길 수 비교
// 값이 같으면 i 값을 1 줄여서 다시 램덤한 수 생성할 수 있도록 설정
for (int j = 0; j < i; j++) {
if (lotto[i] == lotto[j]) {
i--;
break;
}
}
}
// 오름차순으로 정렬
Arrays.sort(lotto);
return lotto;
}
/**
* 구매한 로또 번호와 로또 당첨 번호가 일치하는 수 확인
*
* @param lottoList 구매한 로또 리스트
* @param winningNumber 로또 당첨 번호
* @param count 로또 개수
* @return 당첨번호와 일치한 수를 담은 배열
*/
public static int[] result(ArrayList<int[]> lottoList, int[] winningNumber, int count) {
// 로또 당첨 번호와 일치 여부를 확인할 임시 배열
int[] lotto = new int[6];
// 로또 당첨 번호와 일치하는 수를 담은 배열
int[] resultList = new int[count];
for (int i = 0; i < lottoList.size(); i++) {
// 로또 당첨 번호와 일치하는 수 카운트
int winningCnt = 0;
lotto = lottoList.get(i);
for (int j = 0; j < lotto.length; j++) {
if(lotto[j] == winningNumber[j]) {
winningCnt++;
}
}
resultList[i] = winningCnt;
}
return resultList;
}
/**
* 출력
*
* @param lottoList 구매한 로또 리스트
* @param winningNumber 로또 당첨 번호
* @param resultList 당첨 결과 리스트
*/
public static void print(ArrayList<int[]> lottoList, int[] winningNumber, int[] resultList) {
// 로또 번호 앞 알파벳 생성을 위한 'A' 값 초기화
char alphabet = 65;
// 구매한 로또 출력
for (int i = 0; i < lottoList.size(); i++) {
int[] lotto = lottoList.get(i);
// 마지막을 제외한 로또 번호는 뒤에 ',' 붙여서 출력
System.out.printf("%s\t", alphabet++);
for (int j = 0; j < lotto.length; j++) {
if (j == lotto.length - 1) {
System.out.printf("%02d\n", lotto[j]);
} else {
System.out.printf("%02d,", lotto[j]);
}
}
// 로또는 한 장당 5줄, 알파벳 A ~ E까지만 사용되기 때문에
// 알파벳 E(70)가 되면 로또 구분을 위한 줄바꿈 생성
// 알파벳 E가 되지 않아도 마지막 구매한 로또 번호가 되면 줄바꿈 생성
if (alphabet == 70 || i - (lottoList.size() - 1) == 0) {
System.out.println();
alphabet = 65;
}
}
// 로또 당첨 번호 출력
System.out.printf("[로또 발표]\n\t");
for (int i = 0; i < winningNumber.length; i++) {
if (i == winningNumber.length - 1) {
System.out.printf("%02d\n\n", winningNumber[i]);
} else {
System.out.printf("%02d,", winningNumber[i]);
}
}
// 로또 결과 출력
System.out.println("[내 로또 결과]");
alphabet = 65;
for (int i = 0; i <lottoList.size() ; i++) {
int[] lotto = lottoList.get(i);
// 마지막 로또 번호 다음에는 로또 당첨 번호와 일치하는 수 표시
System.out.printf("%s\t", alphabet++);
for (int j = 0; j < lotto.length; j++) {
if (j == lotto.length - 1) {
System.out.printf("%02d => %d개 일치\n", lotto[j], resultList[i]);
} else {
System.out.printf("%02d,", lotto[j]);
}
}
// 로또는 한 장당 5줄, 알파벳 A ~ E까지만 사용되기 때문에
// 알파벳 E(70)가 되면 로또 구분을 위한 줄바꿈 생성
// 알파벳 E가 되지 않아도 마지막 구매한 로또 번호가 되면 줄바꿈 생성
if (alphabet == 70 || i - (lottoList.size() - 1) == 0) {
System.out.println();
alphabet = 65;
}
}
}
public static void main(String[] args) {
// 로또 개수
int count = 0;
// 구매한 로또 리스트
ArrayList<int[]> lottoList = new ArrayList<>();
// 로또 당첨 번호
int[] winnigNumber;
Scanner sc = new Scanner(System.in);
System.out.printf("[로또 당첨 프로그램]\n\n");
System.out.print("로또 개수를 입력해주세요.(숫자 1 ~10):");
try {
count = sc.nextInt();
if (count < 1 || count > 10) {
throw new RuntimeException("숫자는 1 ~ 10 까지 입력 가능합니다.");
}
} catch (RuntimeException e) {
if (e instanceof InputMismatchException) {
System.out.println(e + ": 숫자만 입력 가능합니다.");
} else {
System.out.println(e);
}
return;
}
// 로또 개수 만큼 로또 번호 생성
for (int i = 0; i < count; i++) {
lottoList.add(lottoGenerator());
}
// 로또 당첨 번호 생성
winnigNumber = lottoGenerator();
// 로또 당첨 번호와 일치하는 수 확인
int[] resultList = result(lottoList, winnigNumber, count);
// 출력
print(lottoList, winnigNumber, resultList);
sc.close();
}
}
Scanner를 통해서 사용자로 부터 로또 구매 개수를 입력받아
int count 변수에 초기화 후 진행
로또 구매 개수는 1 ~ 10까지 가능하기 때문에
구매 개수 범위에서 벗어나면 throw를 통해 예외를 발생시켜 '숫자는 1 ~ 10 까지 입력 가능합니다.' 출력
숫자 이외에 값 입력 시 instanceof로 InputMismatchException 구분해 '숫자만 입력 가능합니다.' 출력
이외에 예외는 e 출력
이후 lottoGenerator() 메소드로 로또 개수 만큼 로또 번호 생성
1 ~ 45 사이의 랜덤한 수 생성을 위해 Random 클래스의 nextInt 사용
중복 값 제거 후 int[] lotto에 6자리 숫자 담아서 진행
이후 로또 당첨 번호 생성 후 int[] winningNumber에 담아서 진행
구매한 로또 번호들과 당첨 로또 번호를 비교해서
일치한 수를 int[] resultList에 담아서 출력을 위한 print() 메소드로 전달
구매한 로또와 내 로또 결과에 로또 번호 표시 시
앞에 A ~ E 알파벳으로 표시하기 때문에
A ~ E 출력 후 줄바꿈 생성하고, 알파벳을 다시 A로 값 변경하며 출력
실행결과
2024.04.13 - [Zero-base] - 가상 선거 및 당선 시뮬레이션 프로그램 제로베이스 백엔드 스쿨 미니과제 6
2024.04.12 - [Zero-base] - 달력 출력 프로그램 제로베이스 백엔드 스쿨 미니과제 5
2024.04.12 - [Zero-base] - 주민등록번호 생성 프로그램 제로베이스 백엔드 스쿨 미니과제 4
2024.04.11 - [Zero-base] - 놀이동산 입장권 계산 프로그램 제로베이스 백엔드 스쿨 미니과제 3
2024.04.11 - [Zero-base] - 결제 금액 캐시백 계산 프로그램 제로베이스 백엔드 스쿨 미니과제 2
2024.04.10 - [Zero-base] - 콘솔 화면에 구구단 출력하기 제로베이스 백엔드 스쿨 미니과제 1
'📌Zero-base' 카테고리의 다른 글
백준 25556번 포스택 제로베이스 자료구조 1일차 주제 : Stack (0) | 2024.04.15 |
---|---|
연소득 과세금액 계산 프로그램 제로베이스 백엔드 스쿨 미니과제 8 (0) | 2024.04.14 |
가상 선거 및 당선 시뮬레이션 프로그램 제로베이스 백엔드 스쿨 미니과제 6 (0) | 2024.04.13 |
달력 출력 프로그램 제로베이스 백엔드 스쿨 미니과제 5 (0) | 2024.04.12 |
주민등록번호 생성 프로그램 제로베이스 백엔드 스쿨 미니과제 4 (0) | 2024.04.12 |