반응형
    
    
    
  
		                                        Notice
		                                        
										
                                    
                                    
                                        Recent Posts
                                        
                                    
                                    
                                        Recent Comments
                                        
                                    
                                    
                                        Link
                                        
                                    
                                | 일 | 월 | 화 | 수 | 목 | 금 | 토 | 
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | |||
| 5 | 6 | 7 | 8 | 9 | 10 | 11 | 
| 12 | 13 | 14 | 15 | 16 | 17 | 18 | 
| 19 | 20 | 21 | 22 | 23 | 24 | 25 | 
| 26 | 27 | 28 | 29 | 30 | 31 | 
                                        Tags
                                        
                                    
                                    - 이클립스
- 인텔리제이
- CMD
- map
- CSS
- 정규식
- HashMap
- ArrayList
- vscode
- table
- 배열
- Java
- js
- Visual Studio Code
- javascript
- IntelliJ
- Button
- date
- list
- 자바
- 자바스크립트
- Array
- string
- json
- Eclipse
- 문자열
- 이탈리아
- replace
- html
- input
                                        Archives
                                        
                                    
                                    - Today
- Total
어제 오늘 내일
[Java] Random 클래스 주요 메소드 및 사용법 본문
Java Random 클래스의 주요 사용법과 예제
Java의 Random 클래스는 난수를 생성하는 데 사용되는 표준 라이브러리 클래스입니다.
이를 사용하면 정수, 실수, 불리언 값 등 다양한 난수를 생성할 수 있습니다.
1. Random 클래스 개요
- java.util.Random 패키지
- Random 객체를 생성하면 시드(seed) 를 기반으로 난수를 생성.
- 정수, 실수, 불리언 값, 바이트 배열 등의 난수를 생성하는 다양한 메서드 제공.
2. Random 클래스 주요 메서드
| nextInt() | int | 모든 정수 범위에서 랜덤 값 반환 | 
| nextInt(n) | int | 0 이상 n 미만의 난수 반환 (0 ≤ 결과 < n) | 
| nextLong() | long | 모든 long 범위에서 난수 반환 | 
| nextFloat() | float | 0.0 이상 1.0 미만의 난수 반환 | 
| nextDouble() | double | 0.0 이상 1.0 미만의 난수 반환 | 
| nextBoolean() | boolean | true 또는 false 반환 | 
| nextBytes(byte[]) | void | 바이트 배열을 채우는 난수 생성 | 
3. 예제
예제 1: Random 객체를 생성하여 난수 생성
import java.util.Random;
public class RandomExample {
    public static void main(String[] args) {
        Random random = new Random(); // Random 객체 생성
        // 정수 난수 생성
        int randomInt = random.nextInt(); // int 범위 내에서 랜덤 값 생성
        System.out.println("랜덤 정수: " + randomInt);
        // 0 이상 100 미만의 난수 생성
        int randomIntWithin100 = random.nextInt(100); // 0~99
        System.out.println("0~99 사이의 랜덤 정수: " + randomIntWithin100);
        // 실수 난수 생성
        double randomDouble = random.nextDouble(); // 0.0 <= x < 1.0
        System.out.println("랜덤 실수 (0~1): " + randomDouble);
        // boolean 값 생성
        boolean randomBoolean = random.nextBoolean();
        System.out.println("랜덤 boolean 값: " + randomBoolean);
    }
}
- Random 객체 생성
- Random random = new Random();
- Random 객체를 생성하면 내부적으로 현재 시간(System.nanoTime())을 기반으로 난수 시드를 설정.
- 이를 통해 항상 다른 난수가 생성됨.
 
- 정수 난수 생성 (nextInt())
- 모든 정수 범위에서 난수를 반환 (int의 범위: -2^31 ~ 2^31-1).
 
- 특정 범위 내의 정수 난수 생성 (nextInt(n))
- nextInt(n)을 사용하면 0 이상 n-1 이하의 난수를 생성 (0 ≤ x < n).
- nextInt(100) → 0 ~ 99 사이의 값 반환.
 
- 실수 난수 생성 (nextDouble())
- nextDouble()은 0.0 이상 1.0 미만 (0 ≤ x < 1.0)의 난수를 생성.
 
- boolean난수 생성 (nextBoolean())
- true 또는 false 중 하나를 랜덤하게 반환.
 
예제 2: Random을 이용한 특정 범위의 난수 생성
import java.util.Random;
public class RandomRangeExample {
    public static void main(String[] args) {
        Random random = new Random();
        // 10 이상 50 이하의 난수 생성
        int min = 10;
        int max = 50;
        int randomNumber = random.nextInt(max - min + 1) + min;
        System.out.println("10~50 사이의 랜덤 정수: " + randomNumber);
    }
}
- 특정 범위(min ~ max) 내의 난수를 생성할 때 공식:
random.nextInt(범위 크기) + 최소값
- random.nextInt(max - min + 1) + min
 → random.nextInt(41) + 10
 → 10 ~ 50 사이의 난수 반환.
예제 3: Random을 이용한 랜덤 비밀번호 생성
import java.util.Random;
public class RandomPasswordGenerator {
    public static void main(String[] args) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
        int length = 8; // 비밀번호 길이
        Random random = new Random();
        StringBuilder password = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(chars.length());
            password.append(chars.charAt(index));
        }
        System.out.println("랜덤 비밀번호: " + password.toString());
    }
}
- chars 문자열에 비밀번호에 사용할 문자들 저장.
- random.nextInt(chars.length())를 사용하여 랜덤 인덱스 선택.
- StringBuilder를 이용해 랜덤하게 선택된 문자들을 조합하여 비밀번호 생성.
출력 예시
랜덤 비밀번호: aZ8!XyP@
결론
- Random 클래스는 정수, 실수, 불리언 값 등 다양한 난수를 생성할 수 있는 강력한 도구
- nextInt(n)을 사용하면 0부터 n-1까지의 난수를 쉽게 생성 가능
- 특정 범위의 난수를 생성하려면 nextInt(max - min + 1) + min을 활용
반응형
    
    
    
  'IT > Java' 카테고리의 다른 글
| [Java] 4자리 수 난수 생성하기 (0) | 2025.03.19 | 
|---|---|
| [Java] Random 클래스의 시드(Seed)란 (0) | 2025.03.18 | 
| [Java] 문자열의 마지막 개행문자 제거하기 (0) | 2025.03.16 | 
| [Java] 문자열 줄바꿈(개행문자) 제거 (0) | 2025.03.15 | 
| [Java] StringBuffer 클래스 사용법 및 예제 (String, StringBuffer, StringBuilder 비교) (0) | 2025.03.14 | 
                              Comments