Java_Random Number
자바에서 난수 생성 (Java Random Number)
자바에서는 난수를 생성하는 다양한 방법을 제공합니다. 난수를 생성할 때는 주로 Math.random()
, Random
클래스, 그리고 **ThreadLocalRandom
**을 사용합니다. 각 방법은 상황에 맞게 사용될 수 있으며, 특정 범위의 난수를 생성하거나 다양한 타입의
난수를 생성할 수 있습니다.
1. Math.random()
을 사용한 난수 생성
Math.random()
메서드는 0.0 이상 1.0 미만의 실수형 난수를 생성합니다. 이 난수를 특정 범위로 변환할 수
있으며, 정수 형태의 난수도 생성할 수 있습니다.
1.1 기본적인 난수 생성
public class Main {
public static void main(String[] args) {
// 0.0 이상 1.0 미만의 난수 생성
double randomValue = Math.random();
// 결과 출력
System.out.println("랜덤 실수: " + randomValue);
}
}
설명:
- *
Math.random()
*은 0.0 이상 1.0 미만의 난수를 반환합니다.
출력:
랜덤 실수: 0.7254214569283171
1.2 특정 범위의 정수 난수 생성
난수를 특정 범위의 정수로 변환하려면 난수에 범위 값을 곱하고 **(int)
**로 형변환을 합니다.
public class Main {
public static void main(String[] args) {
// 1부터 100까지의 난수 생성
int randomInt = (int) (Math.random() * 100) + 1;
// 결과 출력
System.out.println("랜덤 정수 (1~100): " + randomInt);
}
}
설명:
Math.random() * 100
: 0.0 이상 100.0 미만의 난수를 생성합니다.- *
(int)
*로 형변환하여 정수로 변환합니다. - *
+ 1
*을 하여 1부터 100 사이의 난수를 생성합니다.
출력 예시:
랜덤 정수 (1~100): 42
2. Random
클래스를 사용한 난수 생성
자바에서는 Random
클래스를 사용하여 다양한 타입의 난수를 생성할 수 있습니다. Random
클래스는 정수, 실수,
불리언 등의 난수를 생성하는 다양한 메서드를 제공합니다.
2.1 Random
클래스를 사용한 기본 난수 생성
import java.util.Random;
public class Main {
public static void main(String[] args) {
// Random 객체 생성
Random random = new Random();
// 0부터 99 사이의 난수 생성
int randomInt = random.nextInt(100); // 0 이상 100 미만의 정수 난수
System.out.println("랜덤 정수 (0~99): " + randomInt);
// 실수형 난수 생성
double randomDouble = random.nextDouble(); // 0.0 이상 1.0 미만의 실수 난수
System.out.println("랜덤 실수: " + randomDouble);
}
}
설명:
nextInt(100)
: 0부터 99까지의 난수를 생성합니다.nextDouble()
: 0.0 이상 1.0 미만의 실수 난수를 생성합니다.
출력 예시:
랜덤 정수 (0~99): 37
랜덤 실수: 0.8632145432154345
2.2 특정 범위의 난수 생성
Random
클래스는 특정 범위의 난수를 생성하는 데 매우 유용합니다.
import java.util.Random;
public class Main {
public static void main(String[] args) {
// Random 객체 생성
Random random = new Random();
// 50부터 100 사이의 난수 생성
int min = 50;
int max = 100;
int randomInt = random.nextInt((max - min) + 1) + min;
// 결과 출력
System.out.println("랜덤 정수 (50~100): " + randomInt);
}
}
설명:
nextInt((max - min) + 1) + min
:min
과max
사이의 난수를 생성합니다.(max - min) + 1
:min
과max
사이의 난수를 생성하기 위한 범위입니다.
출력 예시:
랜덤 정수 (50~100): 78
2.3 불리언과 바이트 난수 생성
Random
클래스를 사용하면 boolean
타입과 바이트 배열로 난수를
생성할 수 있습니다.
import java.util.Random;
public class Main {
public static void main(String[] args) {
// Random 객체 생성
Random random = new Random();
// 불리언 난수 생성
boolean randomBoolean = random.nextBoolean();
System.out.println("랜덤 불리언: " + randomBoolean);
// 바이트 배열 난수 생성
byte[] byteArray = new byte[5];
random.nextBytes(byteArray);
System.out.print("랜덤 바이트 배열: ");
for (byte b : byteArray) {
System.out.print(b + " ");
}
}
}
설명:
nextBoolean()
: true 또는 false를 반환하는 난수를 생성합니다.nextBytes(byte[])
: 바이트 배열에 난수를 채웁니다.
출력 예시:
랜덤 불리언: true
랜덤 바이트 배열: -95 -47 60 18 -123
3. ThreadLocalRandom
을 사용한 난수 생성 (자바 7 이상)
- *
ThreadLocalRandom
*은 멀티스레드 환경에서 난수를 생성할 때 더 효율적인 방법을 제공합니다. 이 클래스는 각 스레드에 독립적인 난수 발생기를 제공합니다.
3.1 ThreadLocalRandom
을 사용한 난수 생성
import java.util.concurrent.ThreadLocalRandom;
public class Main {
public static void main(String[] args) {
// 1부터 100까지의 난수 생성
int randomInt = ThreadLocalRandom.current().nextInt(1, 101);
System.out.println("랜덤 정수 (1~100): " + randomInt);
// 0.0 이상 1.0 미만의 실수 난수 생성
double randomDouble = ThreadLocalRandom.current().nextDouble();
System.out.println("랜덤 실수: " + randomDouble);
}
}
설명:
ThreadLocalRandom.current().nextInt(min, max)
:min
과max
범위의 난수를 생성합니다. 여기서max
는 포함되지 않으므로 1 이상 101 미만의 난수가 생성됩니다.nextDouble()
: 실수 난수를 생성합니다.
출력 예시:
랜덤 정수 (1~100): 34
랜덤 실수: 0.7153512354625384
4. SecureRandom
을 사용한 보안 난수 생성
자바의 SecureRandom
클래스는 암호학적 보안이 필요한 상황에서 사용하는 난수 생성기입니다. 일반적인 난수보다 예측
가능성이 낮아, 보안 관련 작업에 유용합니다.
4.1 SecureRandom
을 사용한 난수 생성
import java.security.SecureRandom;
public class Main {
public static void main(String[] args) {
// SecureRandom 객체 생성
SecureRandom secureRandom = new SecureRandom();
// 1부터 100까지의 난수 생성
int randomInt = secureRandom.nextInt(100) + 1;
System.out.println("보안 랜덤 정수 (1~100): " + randomInt);
}
}
설명:
- *
SecureRandom
*은 예측할 수 없는 난수를 생성합니다. nextInt(100) + 1
: 1부터 100 사이의 난수를 생성합니다.
출력 예시:
보안 랜덤 정수 (1~100): 67
요약
Math.random()
: 0.0 이상 1.0 미만의 실수 난수를 생성하며, 범위를 조정하여 정수 난수를 생성할 수 있습니다.Random
클래스: 다양한 데이터 타입(정수, 실수, 불리언 등)의 난수를 생성할 수 있습니다.ThreadLocalRandom
: 멀티스레드 환경에서 난수를 더 효율적으로 생성할 수 있습니다.SecureRandom
: 보안이 중요한 경우 사용할 수 있는 난수 생성기입니다.
상황에 맞게 다양한 방법을 사용하여 자바에서 난수를 생성할 수 있습니다.