``` import java.util.Scanner; /* * 질문 * 1.구매한 로또의 숫자가 랜덤 메소드에 의해서 중복 가능성이 있는데 이를 이중 포문으로 돌려서 방지할 때 원리를 잘 모르겠어요 * 2.구매한 로또의 숫자가 정렬되어 있지 않는데 이를 이중포문을 통해 오름차순으로 정렬할 때 원리를 잘 모르겠어요 */ public class LottoGame { // 게임 시작 여부를 결정하는 변수 입니다. String start; // 보너스 번호를 포함한 7개의 당첨번호를 저장할 배열입니다. int[] result = new int[7]; //구매한 로또 번호를 저장할 배열 int[][] lottoArr; Scanner sc = new Scanner(System.in); void ready() { System.out.println("게임을 시작하시겠습니까? (Y/N)"); start = sc.nextLine(); if (start.equals("Y")) { play(); } else if (start.equals("N")) { end(); } else { System.out.print("문자가 잘못 입력 되었습니다. 다시 입력하세요 "); ready(); } } //로또 당첨번호를 오름차순으로 정렬하는 메소드입니다. private void resultSort() { for (int h = 0; h < result.length; h++) { for (int i = 0; i < result.length - 1; i++) { if (result[i] > result[i + 1]) { int temp = result[i]; result[i] = result[i + 1]; result[i + 1] = temp; } } } } void end() { System.out.println("게임을 종료하겠습니다"); } void play() { System.out.print(" 게임 수를 입력하세요 (1~10장)"); // 로또의 매수를 저장하는 변수 입니다. int lottoCount = sc.nextInt(); if (lottoCount == 0 || lottoCount > 11) { System.out.print("게임수가 잘못 입력되었습니다.다시 입력하세요"); play(); //로또를 1~10장 사이로 구매했을 경우 else문이 실행됩니다. } else { // 1~43사이의 수를 랜덤으로 당첨번호 배열에 저장합니다. for (int i = 0; i < result.length; i++) { result[i] = (int) (Math.random() * 43) + 1; for (int j = 0; j < i; j++) { if (result[i] == result[j]) { i--; } } } //구매한 로또의 수만큼 로또번호를 생성 createLottoArr(lottoCount); //구매한 로또를 오름차순으로 정렬하는 메소드 sortLottoArr(lottoCount); //구매한 로또를 출력하는 메소드 printLottoArr(lottoCount); resultSort(); System.out.println("당첨번호 : " + " " + result[0] + " " + result[1] + " " + result[2] + " " + result[3] + " " + result[4] + " " + result[5] + " " + "(" + result[6] + ")"); } } //구매한 로또를 오름차순으로 정렬하는 메소드 private void sortLottoArr(int lottoCount) { for(int i = 0; i < lottoCount; i++) { for(int j = 0; j < 6; j++) { if(j==5){ break; } else { if(lottoArr[i][j] > lottoArr[i][j+1]) { for(int t = 0; t < 5; t++) { int temp = lottoArr[i][j+1]; lottoArr[i][j+1] = lottoArr[i][j]; lottoArr[i][j+1] = temp; } } } } } } //구매한 로또를 출력하는 메소드 private void printLottoArr(int lottoCount) { for (int i = 0; i < lottoCount; i++) { System.out.print(i + 1 + "번:"); for (int j = 0; j < 6; j++) { System.out.print(lottoArr[i][j] + " "); } System.out.println(); } } //구매한 로또를 저장하는 메소드 private void createLottoArr(int lottoCount) { lottoArr = new int[lottoCount][6]; for (int i = 0; i < lottoCount; i++) { for (int j = 0; j < 6; j++) { lottoArr[i][j] = (int) (Math.random() * 43) + 1; } } } public static void main(String[] args) { LottoGame lotto = new LottoGame(); LottoGame lotto1 = new LottoGame(); lotto.ready(); } } ```
# 중복 방지 ArrayList 객체에 로또 번호를 담아서 랜덤하게 꺼내오는 방식을 사용하면 편합니다. 다른 방법으로는 배열을 미리 생성한다음에 섞어주시고 앞에서부터 6개 가져오시면 편해요. # 정렬 방법 위 코드는 버블 정렬 방식을 사용하고있습니다. ArrayList 객체는 자체적으로 소팅 메소드를 가지고 있으니 활용하셔요