View

JAVA : 로또 프로그램 만들기

curioser 2020. 1. 2. 23:47

- Set을 이용해서 로또프로그램 만들기 -> Set을 이용하기 때문에 중복값이 들어가지 않는다.

- TreeSet을 이용해서 정렬이 되게 만들었다

 

import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

public class LottoStore {
	//입력받는 스캐너 메서드
	int input() {
		Scanner input = new Scanner(System.in);
		int in = input.nextInt();
		return in;
	}
	//main을 부르는 메서드
	void mainName() {
		System.out.println("==========================");
		System.out.println("         Lotto 프로그램");
		System.out.println("--------------------------");
		System.out.println("1. Lotto 구입\n2. 프로그램 종료");
		System.out.print("==========================\n메뉴선택 : \t");
	}
	void buyLotto() {
		while(true){
			System.out.println("Lotto 구입 시작");
			System.out.println("(1000원에 로또번호 하나입니다.)");
			System.out.print("금액 입력 : ");
			int money = input();
			
			//1. 입력금액이 1000으로 나눴을 때 0보다 작으면 입력 금액이 너무 적습니다. 로또번호 구입 실패!!!
			// 입력금액이 1000으로 나눴을 때 100보다 크면 입력 금액이 너무 많습니다. 로또번호 구입 실패!!!
			if(money/1000 <= 0) {
				System.out.println("입력 금액이 너무 적습니다. 로또번호 구입 실패!!!");
				return;
			} else if (money/1000 > 100) {
				System.out.println("입력 금액이 너무 많습니다. 로또번호 구입 실패!!!");
				return;
			} else {
				//2. 입력금액이 0~100사이일때 1000으로 나눈 숫자만큼 로또번호 프린트 randLotto()를 while만큼 실행
				System.out.println("\n행운의 로또번호는 아래와 같습니다.");
				for(int i =0 ; i <money/1000; i++) {
					System.out.print("로또번호 " + (i+1) + " : ");
					randLotto();
					System.out.println();
				}
				System.out.println("\n받은 금액은 " + money + "이고  거스름돈은 " + (money%1000) + "원입니다.");
				return;
			}
		}
	}
	void randLotto() {
		Set<Integer> lottery = new TreeSet<>(); //객체를 밖에 만들면 clear()해주어야함
		while(lottery.size() < 6){
			int rand = (int)(Math.random()*45 + 1);
			lottery.add(rand);
		}			
		System.out.print(lottery);
	}
	public static void main(String[] args) {
		LottoStore ls = new LottoStore();
		//1. main부르기
		while(true) {
//			new LottoStore().mainName();
			ls.mainName();
			//2. switch를 통해 1, 2 선택하기
			int num = ls.input();
			
			switch (num) {
			//2-1. buyLotto()
			case 1:
				ls.buyLotto();
				continue;
				//2-1. 종료
			case 2:
				System.out.println("감사합니다.");
				System.exit(0);
			default:
				System.out.println("숫자를 다시 입력해주세요.");
				continue;
			}
		}
	}
}
Share Link
reply
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31