본문 바로가기
JAVA

Java - 배열로 로또 번호를 생성해보자

by 스노위13 2022. 5. 18.

배열을 이용해서 로또 번호를 생성하기

조건

1. 1~45 사이의 랜덤 숫자를 6개 뽑는데 중복을 허용하지 않는다. 

2. 작은 숫자부터 정렬한다.

 

public static void main(String[] args) {
// 로또 번호 생성기
/*
* Array에 랜덤 숫자(1~45)를 6개 넣어주는데 중복을 허용하지 않는다. 반복문이 돌면서 매번 randInt를 생성하고 먼저
* lottoArray에 해당 randInt가 존재하는지 파악한 후 존재하지 않으면 추가하고 존재하면 패스한다.
*/
int[] lottoArray = new int[6];
for (int i = 0; i < lottoArray.length; i++) {
// 1~45 사이의 random 숫자 뽑기 +1을 하지 않으면 0~44까지의 숫자만 뽑는다.
lottoArray[i] = (int) (Math.random() * 45) + 1;
for (int j = 0; j < i; j++) {
if (lottoArray[i] == lottoArray[j]) { // random 숫자의 값 비교
i--; // 만약 새로 뽑은 숫자가 이미 뽑은 숫자와 같다면 i를 빼서 다시 돌린다.
}
}
}
Arrays.sort(lottoArray); // 위에서 뽑은 숫자를 정렬해준다
// 정렬한 숫자를 출력한다.
for (int i = 0; i < lottoArray.length; i++) {
if (i == lottoArray.length - 1) {
System.out.println(lottoArray[i]);
} else {
System.out.print(lottoArray[i] + ", ");
}
}
}
view raw lottoArray.java hosted with ❤ by GitHub

 

콘솔 결과

 

댓글