JAVA/포스팅

자바 java.util.Random클래스

짜집퍼박사(짜박) 2023. 11. 15. 15:50

java.util.Random 클래스는 난수를 생성하기 위한 클래스로, 의사 난수 생성기를 제공합니다. 여러 애플리케이션에서 난수가 필요한 경우에 사용됩니다. 다음은 주요 메서드와 사용법에 대한 간단한 설명입니다.

 

주요 메서드

 

1. nextInt() 메서드

int 범위 내의 난수를 반환합니다.

Random random = new Random();
int randomNumber = random.nextInt();  // int 범위 내의 난수

 

2. nextInt(int bound) 메서드

0부터 bound 사이(제외)의 난수를 반환합니다.

Random random = new Random();
int randomNumberInRange = random.nextInt(10);  // 0부터 9까지의 난수

 

3. nextLong() 메서드

long 범위 내의 난수를 반환합니다.

Random random = new Random();
long randomLong = random.nextLong();  // long 범위 내의 난수

 

4. nextFloat() 메서드

0.0과 1.0 사이의 float 형태의 난수를 반환합니다.

Random random = new Random();
float randomFloat = random.nextFloat();  // 0.0부터 1.0 사이의 난수

 

5. nextDouble() 메서드

0.0과 1.0 사이의 double 형태의 난수를 반환합니다.

Random random = new Random();
double randomDouble = random.nextDouble();  // 0.0부터 1.0 사이의 난수

 

6. nextBoolean() 메서드

boolean 형태의 난수를 반환합니다.

Random random = new Random();
boolean randomBoolean = random.nextBoolean();  // true 또는 false 중 하나의 난수

 

 

예제

import java.util.Random;

public class RandomExample {
    public static void main(String[] args) {
        Random random = new Random();

        // int 범위 내의 난수
        int randomNumber = random.nextInt();
        System.out.println("Random Integer: " + randomNumber);

        // 0부터 9까지의 난수
        int randomNumberInRange = random.nextInt(10);
        System.out.println("Random Integer in Range: " + randomNumberInRange);

        // long 범위 내의 난수
        long randomLong = random.nextLong();
        System.out.println("Random Long: " + randomLong);

        // 0.0부터 1.0 사이의 난수
        float randomFloat = random.nextFloat();
        System.out.println("Random Float: " + randomFloat);

        // 0.0부터 1.0 사이의 난수
        double randomDouble = random.nextDouble();
        System.out.println("Random Double: " + randomDouble);

        // true 또는 false 중 하나의 난수
        boolean randomBoolean = random.nextBoolean();
        System.out.println("Random Boolean: " + randomBoolean);
    }
}

Random 클래스는 간단하게 사용할 수 있고, 난수 생성에 필요한 다양한 메서드를 제공합니다.

 

With ChatGPT