> Java > java지도 시간 > 본문

Java에서 다른 난수를 얻는 방법

王林
풀어 주다: 2020-01-02 09:21:16
원래의
2813명이 탐색했습니다.

Java에서 다른 난수를 얻는 방법

3세대 방법:

1 System.currentTimeMillis()를 통해 현재 시간의 긴 밀리초를 가져옵니다.

2. Math.random()을 통해 0과 1 사이의 double 값을 반환합니다.

3. Random 클래스를 통해 난수를 생성합니다. 강력한 기능을 갖춘 전문 Random 도구 클래스입니다.

첫 번째 방법:

System.currentTimeMillis()를 통해 난수를 가져옵니다. 실제로는 long 유형의 현재 시간을 밀리초 단위로 가져옵니다. 사용 방법은 다음과 같습니다.

final long l = System.currentTimeMillis();
로그인 후 복사

(무료 동영상 튜토리얼 공유: java 동영상 튜토리얼)

int 유형의 정수를 얻으려면 위 결과를 int 유형으로 변환하기만 하면 됩니다. 예를 들어, [0, 100) 사이의 정수를 가져옵니다. 방법은 다음과 같습니다.

final long l = System.currentTimeMillis();
final int i = (int)( l % 100 );
로그인 후 복사

두 번째:

Math.random()을 통해 난수를 얻습니다. 실제로 0(포함)과 1(제외) 사이의 double 값을 반환합니다. 사용법은 다음과 같습니다:

final double d = Math.random();
로그인 후 복사

int 유형의 정수를 얻으려면 위의 결과를 int 유형으로 변환하기만 하면 됩니다. 예를 들어, [0, 100) 사이의 정수를 가져옵니다. 방법은 다음과 같습니다.

final double d = Math.random();
final int i = (int)(d*100);
로그인 후 복사

세 번째 방법:

Random 클래스를 통해 난수를 얻습니다. 사용방법은 다음과 같습니다.

1. Random 객체를 생성합니다. Random 객체를 생성하는 방법에는 다음과 같은 두 가지 방법이 있습니다.

Random random = new Random();//默认构造方法
Random random = new Random(1000);//指定种子数字
로그인 후 복사

(02) Random 객체를 통해 난수를 얻습니다. Random에서 지원되는 임의 값 유형에는 boolean, byte, int, long, float, double이 있습니다.

예를 들어 [0, 100) 사이의 int 정수를 가져옵니다. 방법은 다음과 같습니다.

int i2 = random.nextInt(100);
로그인 후 복사

코드 샘플:

 1 import java.util.Random;
 2 import java.lang.Math;
 3 
 4 /**
 5  * java 的随机数测试程序。共3种获取随机数的方法:
 6  *   (01)、通过System.currentTimeMillis()来获取一个当前时间毫秒数的long型数字。
 7  *   (02)、通过Math.random()返回一个0到1之间的double值。
 8  *   (03)、通过Random类来产生一个随机数,这个是专业的Random工具类,功能强大。
 9  *
10  * @author skywang
11  * @email kuiwu-wang@163.com
12  */
13 public class RandomTest{
14 
15     public static void main(String args[]){
16 
17         // 通过System的currentTimeMillis()返回随机数
18         testSystemTimeMillis();
19 
20         // 通过Math的random()返回随机数
21         testMathRandom();
22 
23         // 新建“种子为1000”的Random对象,并通过该种子去测试Random的API
24         testRandomAPIs(new Random(1000), " 1st Random(1000)");
25         testRandomAPIs(new Random(1000), " 2nd Random(1000)");
26         // 新建“默认种子”的Random对象,并通过该种子去测试Random的API
27         testRandomAPIs(new Random(), " 1st Random()");
28         testRandomAPIs(new Random(), " 2nd Random()");
29     }
30 
31     /**
32      * 返回随机数-01:测试System的currentTimeMillis()
33      */
34     private static void testSystemTimeMillis() {
35         // 通过
36         final long l = System.currentTimeMillis();
37         // 通过l获取一个[0, 100)之间的整数
38         final int i = (int)( l % 100 );
39 
40         System.out.printf("\n---- System.currentTimeMillis() ----\n l=%s i=%s\n", l, i);
41     }
42 
43 
44     /**
45      * 返回随机数-02:测试Math的random()
46      */
47     private static void testMathRandom() {
48         // 通过Math的random()函数返回一个double类型随机数,范围[0.0, 1.0)
49         final double d = Math.random();
50         // 通过d获取一个[0, 100)之间的整数
51         final int i = (int)(d*100);
52 
53         System.out.printf("\n---- Math.random() ----\n d=%s i=%s\n", d, i);
54     }
55 
56 
57     /**
58      * 返回随机数-03:测试Random的API
59      */
60     private static void testRandomAPIs(Random random, String title) {
61         final int BUFFER_LEN = 5;
62 
63         // 获取随机的boolean值
64         boolean b = random.nextBoolean();
65         // 获取随机的数组buf[]
66         byte[] buf = new byte[BUFFER_LEN];
67         random.nextBytes(buf);
68         // 获取随机的Double值,范围[0.0, 1.0)
69         double d = random.nextDouble();
70         // 获取随机的float值,范围[0.0, 1.0)
71         float f = random.nextFloat();
72         // 获取随机的int值
73         int i1 = random.nextInt();
74         // 获取随机的[0,100)之间的int值
75         int i2 = random.nextInt(100);
76         // 获取随机的高斯分布的double值
77         double g = random.nextGaussian();
78         // 获取随机的long值
79         long l = random.nextLong();
80 
81         System.out.printf("\n---- %s ----\nb=%s, d=%s, f=%s, i1=%s, i2=%s, g=%s, l=%s, buf=[",
82                 title, b, d, f, i1, i2, g, l);
83         for (byte bt:buf) 
84             System.out.printf("%s, ", bt);
85         System.out.println("]");
86     }
87 }
로그인 후 복사

추천 관련 기사 및 튜토리얼: java 입문 튜토리얼

위 내용은 Java에서 다른 난수를 얻는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!