Java 응용

Java 응용 (3. 로또 번호 추첨하기)

Kw_w 2024. 3. 5. 21:07

로또 번호 6개를 출력해보자

1. 범위는 1 ~ 45 까지 랜덤으로 번호를 생성

2. 생성된 번호를 배열에 저장

3. 중복 저장이 되지 않도록 한다.

4. 배열에 저장된 6개의 번호를 출력

첫 번째 방법

public class LottoRandom {
    public static void main(String[] args) {
        int[] lotto = new int[6];
        for(int i = 0; i < 6; i++){
            var randNum = (int)(Math.random()*45) + 1;
            var checkFlag = false;
            for(int j = 0; j < 6; j++){
                if(lotto[j]==randNum){
                   checkFlag = true;
                    i--;
                    break;
                }
            }
            if(!checkFlag)lotto[i] = randNum;
        }
        for(var num : lotto){
            System.out.print(num +" ");
        }
    }
}

두 번째 방법

public class LottoRandom {
    public static void main(String[] args) {
        int[] lotto = new int[6];
        boolean[] pickCheck = new boolean[46];

        for (int i = 0; i < lotto.length; i++) {
            while (true) {
                int randNum = (int) (Math.random() * 45) + 1;
                if (!pickCheck[randNum]) {
                    pickCheck[randNum] = true;
                    lotto[i] = randNum;
                    break;
                }
            }
        }

        for (int num : lotto) {
            System.out.print(num + " ");
        }
    }
}