Java는 아래 나열된 일부 내장 메서드와 클래스를 사용하여 난수를 생성하는 세 가지 방법을 제공합니다.
- java.util.Random 클래스 Math.random 메소드 : double형의 난수를 생성할 수 있습니다. ThreadLocalRandom 클래스
1) java.util.Random
- 이 클래스를 사용하여 난수를 생성하려면 먼저 이 클래스의 인스턴스를 만든 다음 해당 인스턴스를 사용하여 nextInt(), nextDouble(), nextLong() 등과 같은 메서드를 호출해야 합니다.
- 이 클래스를 사용하면 정수, 부동 소수점, 이중, 장수, 부울 유형의 난수를 생성할 수 있습니다.
- 생성할 숫자 범위의 상한을 지정하기 위해 메서드에 인수를 전달할 수 있습니다. 예를 들어, nextInt(6)은 0에서 5까지의 범위에 있는 숫자를 생성합니다.
자바
// A Java program to demonstrate random number generation> // using java.util.Random;> import> java.util.Random;> > public> class> generateRandom{> > >public> static> void> main(String args[])> >{> >// create instance of Random class> >Random rand =>new> Random();> > >// Generate random integers in range 0 to 999> >int> rand_int1 = rand.nextInt(>1000>);> >int> rand_int2 = rand.nextInt(>1000>);> > >// Print random integers> >System.out.println(>'Random Integers: '>+rand_int1);> >System.out.println(>'Random Integers: '>+rand_int2);> > >// Generate Random doubles> >double> rand_dub1 = rand.nextDouble();> >double> rand_dub2 = rand.nextDouble();> > >// Print random doubles> >System.out.println(>'Random Doubles: '>+rand_dub1);> >System.out.println(>'Random Doubles: '>+rand_dub2);> >}> }> |
>
>산출
Random Integers: 618 Random Integers: 877 Random Doubles: 0.11981638980670772 Random Doubles: 0.7288425427367139>
2) 수학.랜덤()
Math 클래스에는 지수 계산, 로그 계산 등과 같은 다양한 숫자 연산을 수행하기 위한 다양한 메서드가 포함되어 있습니다. 이러한 메서드 중 하나는 random()이며, 이 메서드는 0.0보다 크거나 같고 1.0보다 작은 양의 부호가 있는 double 값을 반환합니다. . 반환된 값은 의사 무작위로 선택됩니다. 이 방법은 Double 유형의 난수만 생성할 수 있습니다. 아래 프로그램에서는 이 방법을 사용하는 방법을 설명합니다.
자바
피트 데이비슨
// Java program to demonstrate working of> // Math.random() to generate random numbers> import> java.util.*;> > public> class> generateRandom> {> >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.40748894116045375 Random doubles: 0.006683607229094002>
3) java.util.concurrent.ThreadLocalRandom 클래스
이 클래스는 정수, 복식, 부울 등의 난수를 생성하기 위해 Java 1.7에 도입되었습니다. 아래 프로그램에서는 이 클래스를 사용하여 난수를 생성하는 방법을 설명합니다.
자바
// Java program to demonstrate working of ThreadLocalRandom> // to generate random numbers.> import> java.util.concurrent.ThreadLocalRandom;> > public> class> generateRandom> {> >public> static> void> main(String args[])> >{> >// Generate random integers in range 0 to 999> >int> rand_int1 = ThreadLocalRandom.current().nextInt();> >int> rand_int2 = ThreadLocalRandom.current().nextInt();> > >// Print random integers> >System.out.println(>'Random Integers: '> + rand_int1);> >System.out.println(>'Random Integers: '> + rand_int2);> > >// Generate Random doubles> >double> rand_dub1 = ThreadLocalRandom.current().nextDouble();> >double> rand_dub2 = ThreadLocalRandom.current().nextDouble();> > >// Print random doubles> >System.out.println(>'Random Doubles: '> + rand_dub1);> >System.out.println(>'Random Doubles: '> + rand_dub2);> > >// Generate random booleans> >boolean> rand_bool1 = ThreadLocalRandom.current().nextBoolean();> >boolean> rand_bool2 = ThreadLocalRandom.current().nextBoolean();> > >// Print random Booleans> >System.out.println(>'Random Booleans: '> + rand_bool1);> >System.out.println(>'Random Booleans: '> + rand_bool2);> >}> }> |
프라임 자바에는 코드가 없습니다
>
>산출
Random Integers: -2106603442 Random Integers: 1894823880 Random Doubles: 0.6161052280172054 Random Doubles: 0.8418944588752132 Random Booleans: false Random Booleans: true>
특정 범위의 난수를 생성합니다. 이를 수행하는 두 가지 방법이 있습니다.
- 무작위 클래스 사용
- Math.random() 메소드 사용
1. 무작위 클래스 사용
다음은 특정 범위의 난수를 생성하는 공식입니다. 여기서 최소 및 최대는 숫자의 하한 및 상한입니다.
자바 하위 문자열 방법
무작위 랜드 = 새로운 무작위();
int randomNum = rand.nextInt(max – min + 1) + min;
자바
import> java.io.*;> import> java.util.*;> class> GFG {> >public> static> void> main (String[] args) {> >Random rand =>new> Random();> >int> max=>100>,min=>50>;> >System.out.println(>'Generated numbers are within '>+min+>' to '>+max);> >System.out.println(rand.nextInt(max - min +>1>) + min);> >System.out.println(rand.nextInt(max - min +>1>) + min);> >System.out.println(rand.nextInt(max - min +>1>) + min);> >}> }> |
>
>산출
Generated numbers are within 50 to 100 58 87 55>
시간 복잡도: O(1)의 시간 복잡도를 갖습니다.
보조 공간: O(1)에는 일정한 공간이 필요합니다.
2. Math.random() 메소드 사용
다음은 특정 범위의 난수를 생성하는 공식입니다. 여기서 최소 및 최대는 숫자의 하한 및 상한입니다.
int randomNum = min + (int)(Math.random() * ((max – min) + 1));
자바
/*package whatever //do not write package name here */> import> java.io.*;> import> java.util.*;> class> GFG {> >public> static> void> main (String[] args) {> >int> max=>100>,min=>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 53 99 77>
시간 복잡도: O(1)의 시간 복잡도를 갖습니다.
보조 공간: O(1)에는 일정한 공간이 필요합니다.