Home Java javaTutorial How to get different random numbers in java

How to get different random numbers in java

Jan 02, 2020 am 09:21 AM
java method Obtain random number

How to get different random numbers in java

Three generation methods:

1. Get a long type of current time milliseconds through System.currentTimeMillis() number.

2. Return a double value between 0 and 1 through Math.random().

3. Generate a random number through the Random class. This is a professional Random tool class with powerful functions.

First type:

Get random numbers through System.currentTimeMillis(). It actually gets the current time in milliseconds, which is of type long. The usage method is as follows:

1

final long l = System.currentTimeMillis();

Copy after login

(Free video tutorial sharing: java video tutorial)

If you want to get an integer of type int, you only need to convert the above result to int Just type. For example, get an integer between [0, 100). The method is as follows:

1

2

final long l = System.currentTimeMillis();

final int i = (int)( l % 100 );

Copy after login

Second:

Get random numbers through Math.random(). In fact, it returns a double value between 0 (inclusive) and 1 (exclusive). The usage method is as follows:

1

final double d = Math.random();

Copy after login

To obtain an integer of type int, you only need to convert the above result to type int. For example, get an integer between [0, 100). The method is as follows:

1

2

final double d = Math.random();

final int i = (int)(d*100);

Copy after login

The third method:

Get random numbers through the Random class. The usage method is as follows:

1. Create a Random object. There are two methods to create Random objects, as follows:

1

2

Random random = new Random();//默认构造方法

Random random = new Random(1000);//指定种子数字

Copy after login

(02) Get random numbers through Random objects. Random value types supported by Random include: boolean, byte, int, long, float, double.

For example, get the int integer between [0, 100). The method is as follows:

1

int i2 = random.nextInt(100);

Copy after login

Code example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

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 }

Copy after login

Recommended related articles and tutorials: java introductory tutorial

The above is the detailed content of How to get different random numbers in java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles