Java_25_Random 난수 클래스

OngTK·2025년 8월 15일

Java

목록 보기
25/35

1. Random, 난수 클래스


1) 사용법

(1) Random 객체 생성

Random random = new Random();

(2) 주요 메소드

.nextInt() : int 타입·허용 범위 내의 난수 생성
.nextInt( n ) : 0부터 (n-1) 값 까지 사이의 난수 생성
.nextInt( m ) + n : n 값부터 m 개의 사이의 난수 생성
.nextDouble() : 0~1 사이의 실수인 난수 생성
.nextBoolean() : true · false 중 랜덤

public class Example {
    public static void main(String[] args) {
        // 1. Random 객체 생성
        Random random = new Random();
        System.out.println(random);

        int value1 = random.nextInt();
        System.out.println("value1 = " + value1);

        // 2. 1 ~ 9 사이의 난수 생성
        int value2 = random.nextInt(10) + 1;
        System.out.println(value2);

        // 3. 0 ~ 99 사이의 난수 발생
        int value3 = random.nextInt(100);

        // 4. 0 ~ 1 사이의 실수 생성
        double value4 = random.nextDouble();
        System.out.println(value4);

        // 5. random boolean
        boolean value5 = random.nextBoolean();
        System.out.println(value5);
    }
}

2) 활용

(1) 복수 데이터 중 하나의 데이터를 임의로 선택

public class Example {
    public static void main(String[] args) {
        ArrayList<String> nameList = new ArrayList<>();
        nameList.add("배두훈");
        nameList.add("강형호");
        nameList.add("조민규");
        nameList.add("고우림");

        String name = nameList.get(random.nextInt(nameList.size()));
        System.out.println(name);
    }
}

(2) 임의의 6자리 영문자 인증코드 만들기(아스키코드 패턴 활용)

public class Example {
    public static void main(String[] args) {
        String code = "";
        for (int i = 1; i <= 6; i++) {
            // a : 97 ~ z : 122
            Random ran = new Random();
            int val = ran.nextInt(26) + 97;     // 97 부터 26개(122번) 까지 중 랜덤
            char str = (char) val;              // 아스키코드 번호를 char 문자로 변환
            code += str;
        }
        System.out.println(code);
    }
}

(3) 아스키코드 패턴이 없는 난수 코드

아스키코드 패턴이 없을 경우, 데이터 배열을 만들고 random으로 추출

public class Example {
    public static void main(String[] args) {
        char[] ranStr = {'0', '1', '2', 'a', 'b', 'c', 'Z', 'Y'};

        String newPwd = "";
        for (int i = 1; i <= 6; i++) {
            Random ran = new Random();
            int index = ran.nextInt(ranStr.length);
            newPwd += ranStr[index];
        }
        System.out.println(newPwd);
    }
}

(4) 주사위

public class Example {
    public static void main(String[] args) {
        int dice = random.nextInt(6) + 1;
        System.out.println(dice);
    }
}

(5) 로또 번호 반환

public class Example {
    public static void main(String[] args) {
        ArrayList<Integer> lottoList = new ArrayList<>();
        
        // [방법 1]
        for (int i = 1; i <= 6; i++) {
            int lotto = random.nextInt(45) + 1;
            if(lottoList.contains(lotto)){      // lotto 번호가 이미 List에 존재한다면
                i--;                            // 횟수를 원래대로 돌려놓고
                continue;                       // 넘어가기
            }
            lottoList.add(lotto);
        }
        System.out.println(lottoList);

        // [방법 2]
        ArrayList<Integer> lottoList2 = new ArrayList<>();
        for (;;) {
            int lotto = random.nextInt(45) + 1;
            if(lottoList2.contains(lotto)){      // lotto 번호가 이미 List에 존재한다면
                continue;
            }
            lottoList2.add(lotto);
            if(lottoList2.size() == 6 ) break;
        }
        System.out.println(lottoList2);
    }
}

(6) 문자열 내에서 무작위 반환

public class Example {
    public static void main(String[] args) {
        String ranStr2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        // 문자열 길이
        int strlen = ranStr2.length();
        // 문자열 길이의 난수 생성
        int ranIndex = random.nextInt( strlen );
        char str1 = ranStr2.charAt(ranIndex);
        System.out.println(str1);
    }
}
profile
2025.05.~K디지털_풀스택 수업 수강중

0개의 댓글