logo

Java에서 난수 생성

난수 시뮬레이션 게임 보안 등을 위한 프로그래밍에 널리 사용됩니다. Java에 내장된 메서드와 클래스를 사용하여 난수를 생성하는 방법에는 여러 가지가 있습니다. 가장 일반적으로 사용되는 접근 방식은 다음과 같습니다.

  • java.util.Random 클래스
  • Math.random() 메서드(이중 값 반환)
  • ThreadLocalRandom 클래스(Java 7에서 도입됨)

이러한 각 접근 방식을 하나씩 자세히 살펴보겠습니다.

1. java.util.Random 사용

이 클래스의 도움으로 우리는 다양한 유형의 난수를 생성할 수 있습니다(int double long boolean 등).



주요 방법:

  • nextInt(): 이 방법은 임의의 정수(음수를 포함한 전체 범위)를 생성합니다.
  • nextInt(int 바운드): 이 방법은 0(포함)과 경계(제외) 사이의 임의의 정수를 생성합니다.
  • 다음더블(): 이 방법은 0.0(포함)과 1.0(제외) 사이에서 임의의 double을 생성합니다.
  • 다음부울(): 무작위 참 또는 거짓

:

Java
// Generating random number using java.util.Random; import java.util.Random; public class Geeks{    public static void main(String[] args) {    // Creating the instance of Random class  Random r= new Random();  // Generate random integers in range 0 to 999  int r1 = r.nextInt(1000);  int r2 = r.nextInt(1000);  // Printing random integers  System.out.println('Random Integers: ' + r1);  System.out.println('Random Integers: ' + r2);  // Generate random doubles  double rd1 = r.nextDouble();  double rd2 = r.nextDouble();  // Printing random doubles  System.out.println('Random Doubles: ' + rd1);  System.out.println('Random Doubles: ' + rd2);  } } 

산출
Random Integers: 39 Random Integers: 190 Random Doubles: 0.4200728082969115 Random Doubles: 0.9327571841228275 

특정 범위의 숫자 생성

특정 범위의 난수를 생성하는 공식은 다음과 같습니다.

무작위 랜드 = 새로운 무작위();

int randomNum = rand.nextInt(max - min + 1) + min;

메모: min 및 max는 숫자의 하한 및 상한입니다.

예:

Java
// Generating random number in a specific range  import java.io.*; import java.util.*; class Geeks {    public static void main (String[] args) {  Random r = new Random();  int max=100min=50;  System.out.println('Generated numbers are within '+ min +' to '+ max);  System.out.println(r.nextInt(max - min + 1) + min);  System.out.println(r.nextInt(max - min + 1) + min);  System.out.println(r.nextInt(max - min + 1) + min);  } } 

산출
Generated numbers are within 50 to 100 55 51 51 


2. Math.random() 사용

그만큼 수학 수업 지수 로그 계산 등과 같은 다양한 수치 연산을 수행하는 다양한 방법이 포함되어 있습니다. 이러한 방법 중 하나는 다음과 같습니다. 무작위의() 이 메서드는 0.0보다 크거나 같고 1.0보다 작은 양수 부호를 사용하여 double 값을 반환합니다. 반환된 값은 의사 무작위로 선택됩니다. 이 방법은 Double 유형의 난수만 생성할 수 있습니다.

예:

Java
// Java program to demonstrate working of  // Math.random() to generate random numbers import java.util.*;   public class Geeks {  public static void main(String args[])  {  // Generating random doubles  System.out.println('Random doubles: ' + Math.random());  System.out.println('Random doubles: ' + Math.random());  } } 

산출
Random doubles: 0.38601320746656065 Random doubles: 0.9209882942481417 

특정 범위의 숫자 생성

다음은 최소값과 최대값이 숫자의 하한 및 상한인 특정 범위의 난수를 생성하는 공식입니다.

int randomNum = min + (int)(Math.random() * ((max - min) + 1));

예:

Java
// Demonstrating how to generate random  // number within a specific range import java.io.*; import java.util.*; class Geeks {    public static void main (String[] args) {  int max=100min=50;  System.out.println('Generated numbers are within '+min+' to '+max);  System.out.println(min + (int)(Math.random() * ((max - min) + 1)));  System.out.println(min + (int)(Math.random() * ((max - min) + 1)));  System.out.println(min + (int)(Math.random() * ((max - min) + 1)));   } } 

산출
Generated numbers are within 50 to 100 82 68 77 


3. ThreadLocalRandom 사용

이는 경합을 줄이기 때문에 다중 스레드 환경에서 권장되는 방법입니다.

주요 방법:

  • 현재().nextInt(): 임의의 정수(전체 범위)
  • current().nextInt(최소 최대 + 1): 범위 내 임의의 정수(제한된 예를 추가했습니다)
  • 현재().nextDouble(): 랜덤 더블(0.0 ~ 1.0)
  • 현재().nextBoolean(): 무작위 참 또는 거짓

예:

라텍스 매트릭스
Java
// Demonstrates how to generate random integers  // doubles and booleans using ThreadLocalRandom import java.util.concurrent.ThreadLocalRandom; public class Geeks {  public static void main(String[] args) {  // Generate random integers in range 0 to 999  // Random number between 0 and 999  int r1 = ThreadLocalRandom.current().nextInt(1000);    // Random number between 0 and 999  int r2 = ThreadLocalRandom.current().nextInt(1000);   // Print random integers  System.out.println('Random Integers: ' + r1);  System.out.println('Random Integers: ' + r2);  // Generate Random doubles between 0.0 (inclusive)   // and 1.0 (exclusive)  double rd1 = ThreadLocalRandom.current().nextDouble();  double rd2 = ThreadLocalRandom.current().nextDouble();  // Print random doubles  System.out.println('Random Doubles: ' + rd1);  System.out.println('Random Doubles: ' + rd2);  // Generate random booleans  boolean rb1 = ThreadLocalRandom.current().nextBoolean();  boolean rb2 = ThreadLocalRandom.current().nextBoolean();  // Print random Booleans  System.out.println('Random Booleans: ' + rb1);  System.out.println('Random Booleans: ' + rb2);  } } 

산출
Random Integers: 812 Random Integers: 461 Random Doubles: 0.7420865203902993 Random Doubles: 0.9580683365617423 Random Booleans: false Random Booleans: false