Java

java IO) 로또 생성기 + 출력스트림

조충희 2025. 6. 3. 10:13

난수를 만들고 이를 파일출력스트림을 통해 텍스트 파일에 출력해봤다

1.경로지정

2.출력스트림

3.난수생성

4.실행의흐름

public class LottoByte {
    public static void main(String[] args) {
        Random random = new Random();
        int [] lotto = new int[6];

        String destinationFilePath = "test.txt";

        try (FileOutputStream fos = new FileOutputStream(destinationFilePath,true)) {

            for (int i = 0; i < lotto.length; i++) {
                lotto[i] = (random.nextInt(45) + 1);
                for (int j = 0; j < i; j++) {
                    if (lotto[i] == lotto[j]) {
                        i--;
                        break;
                    }
                }
                fos.write((String.valueOf(lotto[i])+" ").getBytes());
            }
            fos.write(("\n").getBytes());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }//try-catch
    }//end of main
}//end of class

3벌의 로또번호를 입력했다.

중복번호 방어코드를 썼음에도 불구하고 반복되는 번호가 나오는 것이 보인다.

이 문제의 해결법은

1. set 자료구조 활용

2. 더 탄탄한 방어코드 작성이다.

 

예제2)

set 자료구조를 활용한 로또 생성기 + 파일출력스트림

1. set 집합, 경로생성

2. 파일 출력스트림

3. 난수생성(while)

4. set 자료를 ArrayList 배열에 옮겨 정렬

5. 실행의흐름

public class Lottobyte02 {
    public static void main(String[] args) {

        Set<Integer> lotto = new HashSet<>();
        String filePath = "test.txt";
        Random random = new Random();

        try (FileOutputStream fos = new FileOutputStream(filePath)){
            //난수생성
            while (lotto.size() < 6) {
                int num = random.nextInt(45) + 1;
                lotto.add(num);
            }
            //오름차순 정렬
            List<Integer> sortedLotto = new ArrayList<>(lotto);
            Collections.sort(sortedLotto);
            //실행의흐름
            for (int number : sortedLotto) {
                fos.write((number + " ").getBytes());
            }
            fos.write("\n".getBytes());
            System.out.println(sortedLotto);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }//main
}//class

 

예제3)

기존 방어코드를 보강해보자

1.배열 및 경로생성

2.출력스트림 준비

3.난수생성

4.방어코드 + 강화된 조건문

5.실행의 흐름

public class LottoBytes03 {
    public static void main(String[] args) {

        //배열 및 경로 생성
        Random random = new Random();
        int[] lotto = new int[6];
        String filePath = "test.txt";

        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            //난수생성
            for (int i = 0; i < lotto.length; ) {
                int num = random.nextInt(45) + 1;
                boolean isDuplicate = false;
                //중복방지 방어코드
                for (int j = 0; j < i; j++) {
                    if (lotto[j] == num) {
                        isDuplicate = true;
                        break;
                    }
                }
                //중복이 아닐때만 배열에 입력하고 다음 순서로 넘어간다
                if (!isDuplicate) {
                    lotto[i] = num;
                    i++;
                }
            }
            //오름차순 정렬
            Arrays.sort(lotto);

            //실행의 흐름
            System.out.print("로또 번호: ");
            for (int num : lotto) {
                fos.write((num + " ").getBytes());
                System.out.print(num + " ");
            }
            fos.write("\n".getBytes());

        } catch (Exception e) {
            e.printStackTrace();
        }//t-c
    }//main
}//class