📢 로또 추첨기
- 사용자 로또번호 자동생성(auto), 수동(입력받아서) 번호 저장
- 당첨번호를 입력받음
- 결과를 확인
📢 프로그램 구조
Lotto 클래스
🔷 필드
numbers[]: 사용자의 로또 번호를 저장하는 배열.
st: 회차 정보.
🔷 메서드
random(): 1~45 범위의 랜덤 숫자 생성
randomLotto(): 6개의 랜덤 번호 생성(중복X)
isContain(int num): 배열에 숫자 중복 여부
insertNumbers(int arr[]): 수동으로 입력된 번호를 배열에 저장
toString(): 객체 출력
LottoExtend 클래스
🔷 필드
bonus: 보너스 번호
🔷 주요 메서드
randomLotto(): 기본 번호 생성 후 보너스 번호 추가
insertNumbers(int[] arr, int bonus): 6자리 번호 + 보너스 번호 저장
LottoController 클래스
🔷 주요 기능:
createLotto(Scanner scan): 수동으로 로또 번호 입력받음.
createLottoAuto(): 자동 로또 번호 생성
insertLotto(Scanner scan): 당첨 번호를 입력받음.
checkLotto(): 입력된 로또 번호와 가장 최근의 당첨 번호를 비교하고, 등수를 매김
printLotto(): 저장된 당첨 번호 리스트 출력
LottoMain 클래스
메인 메서드: 사용자로부터 메뉴 입력을 받아서 각 기능을 호출.
package lotto;
import java.util.Scanner;
public class LottoMain {
public static void main(String[] args) {
// 로또 프로그램
/* --menu--
* 1. 로또 번호 생성 (수동) : 사용자가 직접 번호 입력
* 2. 로또 번호 생성 (자동) : Random
* 3. 당첨번호 입력(수동,자동) : 사용자가 직접 입력
* 4. 당첨확인 : 가장 마지막에 발행한 당첨번호로 확인
* 5. 역대 당첨번호 목록 확인
* 6. 종료
*
* 로또는 상속을 하여 사용
* Lotto class => 사용자의 번호를 저장하는 클래스
* LottoExtend class => 당첨번호 클래스 Lotto를 상속 + 보너스번호
* LottoController => 처리
* */
Scanner scan = new Scanner(System.in);
LottoController lc = new LottoController();
int menu = 0;
do {
System.out.println("--menu--");
System.out.println("1. 로또 번호 생성 (수동)|2. 로또 번호 생성 (자동)");
System.out.println("3. 당첨번호 입력(수동,자동)|4. 당첨확인|5. 역대 당첨번호확인|6. 종료");
System.out.println("menu>");
menu = scan.nextInt();
switch(menu) {
case 1: lc.createLotto(scan); break;
case 2: lc.createLottoAuto(); break;
case 3: lc.insertLotto(scan); break;
case 4: lc.checkLotto(); break;
case 5: lc.printLotto(); break;
case 6: System.out.println("종료"); break;
default: System.out.println("잘못된 메뉴~!!");
}
}while(menu != 6);
scan.close();
}
}
package lotto;
import java.util.Scanner;
public class LottoController {
//당첨번호는 여러개 배열로 저장
private LottoExtend lotto[] = new LottoExtend[5];
private int lCount=0;
//사용자 변호는 1개
private Lotto user = new Lotto();
private int st = 0; //회차 값
public void createLotto(Scanner scan) {
// 수동 로또번호 입력
System.out.println("로또번호입력(중복X, 1~45, 숫자6개)>");
int tmp[] = new int[6];
for(int i=0; i<tmp.length; i++) {
tmp[i] = scan.nextInt();
}
if(isDuplicated(tmp)) {
System.out.println("오류발생. 다시입력하세요!!");
}else {
user.insertNumbers(tmp);
user.st = this.st+1;
System.out.println(user);
}
}
//수동으로 입력되는 로또번호의 중복체크, 범위체크
public boolean isDuplicated(int arr[]) {
//중복확인
for(int i=0; i<arr.length; i++) {
for(int j=i+1; j<arr.length; j++) {
if(arr[i] == arr[j]) {
return true;
}
}
}
//범위확인
for(int i=0; i<arr.length; i++) {
if(arr[i]<0 || arr[i]>45) {
return true;
}
}
return false;
}
public void createLottoAuto() {
// 자동 로또번호 입력
user.randomLotto();
user.st = this.st+1;
System.out.println(user);
}
public void insertLotto(Scanner scan) {
// 당첨번호 수동생성
System.out.println("당첨번호입력(중복X, 1~45, 숫자7개)>");
int tmp[] = new int[6];
for(int i=0; i<tmp.length; i++) {
tmp[i] = scan.nextInt();
}
int bonus = scan.nextInt();
if(isDuplicated(tmp)) {
System.out.println("오류발생. 다시입력하세요!!");
}else {
LottoExtend tmpLotto = new LottoExtend();
tmpLotto.insertNumbers(tmp, bonus);
this.st++;
tmpLotto.st = st;
lotto[lCount] = tmpLotto;
lCount++;
System.out.println(tmpLotto);
}
}
public void checkLotto() {
// 당첨번호와 유저번호를 체크하여 등수를 출력
// 사용자번호와 가장 마지막 당첨번호를 확인하여 등수를 출력
if(user.isContain(0)) { //모든 값이 다 채워지지 않았거나 하나도 채워지지 않을경우
System.out.println("체크할 번호가 없습니다.");
return;
}
//당첨번호가 없을 경우
if(lCount==0) {
System.out.println("당첨번호가 없습니다.");
return;
}
int cnt = 0;
//가장 마지막 당첨번호 저장
LottoExtend tmp = lotto[lCount-1];
//회차 일치여부 확인
if(tmp.getSt() != user.getSt()) {
System.out.println("회차가 맞지 않습니다.!!");
return;
}
//for문으로 일치하는 개수 확인
for(int i=0; i<user.getNumbers().length; i++) {
int num = tmp.getNumbers()[i];
if(user.isContain(num)) {
cnt++;
}
}
int rank = -1;
switch(cnt) {
case 6: rank = 1; break;
case 5:
if(user.isContain(tmp.getBonus())) {
rank = 2;
}else {
rank = 3;
}
break;
case 4: rank = 4; break;
case 3: rank = 5; break;
default:
System.out.println("꽝~!!");
}
if(rank != -1) {
System.out.println(rank+"등 당첨~!!");
}
}
public void printLotto() {
// 역대 당첨번호 리스트 확인
System.out.println("--당첨번호리스트--");
for(int i=0; i<lCount; i++) {
System.out.println(lotto[i]);
}
}
}
package lotto;
import java.util.Arrays;
// Math.random() 같은 효과
import java.util.Random;
public class Lotto {
// 나도 쓰지만 상속 해줘야 함.
protected int numbers[] = new int[6]; //사용자번호 + 당첨번호 같이 사용하는 배열
protected int st; //회차
//유지보수를 편리하게 하기위해
protected int random() {
return new Random().nextInt(45)+1;
}
// 1. 랜덤번호 6개를 numbers[]에 채우는 메서드 (중복제거)
protected void randomLotto() {
//배열초기화
init();
int cnt=0;
while(cnt < numbers.length) {
int r = random();
if(!isContain(r)) {
numbers[cnt] = r;
cnt++;
}
}
}
// 2. 중복제거 메서드 중복이 있으면 true / false (범위 체크도 같이)
protected boolean isContain(int num) {
if(num <0 || num >45) {
//오류발생
throw new RuntimeException("숫자의 범위는 1~45까지 입니다.");
}
for(int tmp : numbers) {
if(tmp == num) {
return true;
}
}
return false;
}
// 3. 배열초기화
protected void init() {
numbers = new int[6]; //기존 배열 버리고 새배열로 추가
}
// 4. 번호 수동생성
//(수동 생성된 번호(이미 중복제거 확인 후 넘어오는 배열)를 numbers[] 에 배열복사)
protected void insertNumbers(int arr[]) {
if(arr.length > numbers.length) { // 7자리는 허용
throw new RuntimeException("배열의 길이를 확인하세요.");
}
// 만약 7자리의 값을 가져오면 마지막 1자리를 버리겠다.
System.arraycopy(arr, 0, numbers, 0, numbers.length);
}
// 5. 번호확인메서드 => toString()
@Override
public String toString() {
return st+"회차 "+Arrays.toString(numbers);
}
public int[] getNumbers() {
return numbers;
}
public void setNumbers(int[] numbers) {
this.numbers = numbers;
}
public int getSt() {
return st;
}
public void setSt(int st) {
this.st = st;
}
}
package lotto;
public class LottoExtend extends Lotto {
// Lotto 클래스를 상속받아서 보너스 처리만 하면 됨.
private int bonus; //보너스 번호만 있으면 됨.
@Override
protected void randomLotto() {
// 기존 numbers 6자리 배열 채우기는 이미 완성
//기존 번호에 중복없이 보너스 번호 생성
super.randomLotto();
while(true) {
int r = random();
if(!isContain(r)) {
bonus= r;
break;
}
}
}
@Override
protected void init() {
// 배열 초기화
super.init(); //numbers 배열을 새로만들어 놓은 상태
bonus = 0;
}
@Override
protected void insertNumbers(int[] arr) {
// 가져온 번호가 7자리일 경우...
super.insertNumbers(arr); //6자리만 넣기
this.bonus = arr[numbers.length]; //6번지 채우기 나머지는 버리기
}
protected void insertNumbers(int[] arr, int bonus) {
// 가져온 번호는 6자리, 보너스를 별도로 가져오는 경우...
super.insertNumbers(arr);
this.bonus = bonus;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return super.toString()+"["+bonus+"]";
}
public int getBonus() {
return bonus;
}
public void setBonus(int bonus) {
this.bonus = bonus;
}
}'백엔드 > Java' 카테고리의 다른 글
| 객체지향 프로그래밍 (1) | 2024.10.14 |
|---|---|
| Java로 학생 정보 관리 시스템 구현(3) (0) | 2024.10.13 |
| Java 인터페이스 (0) | 2024.10.11 |
| Java로 상품 관리 시스템 구현(2) (0) | 2024.10.10 |
| Java로 상품 관리 시스템 구현(1) (0) | 2024.10.08 |