로또 번호는 1 ~ 45번까지 있으며 이 중에서 중복되지 않는 6개의 숫자를 추출하여 결과를 출력한다.
package Chapter05;
import java.util.Random;
public class Exercise52 {
public static void main(String[] args) {
int lotto[] = new int[6];
for (int i = 0; i < 6; i++) {
Random random = new Random();
int c = random.nextInt(45) + 1;
lotto[i] = c;
for (int j = 0; j < i; j++) {
if (lotto[i] == lotto[j]) {
i--;
break;
}
}
System.out.println("로또 번호: " + lotto[i]);
}
}
}
선생님 답안 첫번째 방법
package Chapter05;
import java.util.Random;
public class dd {
public static void main(String[] args) {
int[] lotto = new int[6];
Random random = new Random();
for (int i = 0; i < lotto.length; i++) {
lotto[i] = random.nextInt(45) + 1;
for (int j = 0; j < i; j++) {
if (lotto[j] == lotto[i]) {
i--;
}
}
}
for (int i = 0; i < lotto.length; i++) {
System.out.println(lotto[i] + "");
}
}
}
두번째 방법
int[] balls = new int[45];
for (int i = 0; i<balls.length; i++){
balls[i] = i +1 ;
}
for (int i = 0; i < balls.length; i++){
int ranNum = random.nextInt(45);
int temp = balls[i];
balls[i]=balls[ranNum];
balls[ranNum]=temp;
}
//섞인 공에서 앞의 6개 잘라서 lotto에 넣기
for (int i=0;i<lotto.length;i++) {
lotto[i]=balls[i];
}
//출력
for (int i=0; i<lotto.length;i++) {
System.out.println(lotto[i]+" ");
}
'Java > 과제' 카테고리의 다른 글
chapter05) 참조타입 example - 주사위를 던져서 각 면이 나오는 횟수를 출력하는 프로그램 (0) | 2022.08.17 |
---|---|
chapter05) 참조타입 example - 인공지능 컴퓨터와 게이머(사람)가 가위바위보 게임을 할 수 있는 프로그램 (0) | 2022.08.17 |
chapter05) 참조타입 example - 최댓값과 최솟값을 구하시오. (2) | 2022.08.17 |
chapter04) 조건문과 반복문 example - 랜덤 숫자 맞추는 게임 프로그램 (0) | 2022.08.10 |
chapter04) 조건문과 반복문 example - 가위바위보 게임 프로그램 (0) | 2022.08.10 |