Home >Java >javaTutorial >What are the ways to create random numbers in Java?

What are the ways to create random numbers in Java?

WBOY
WBOYforward
2023-05-01 14:52:151304browse

    The first time I came into contact with random numbers was using rand() in the C language; but when I execute it again, I will find that, eh, it is actually the same as the last execution. The result is the same. Because there is no initialized seed, the system uses a unified seed. At this time, the random numbers generated will be the same every time. In this case, srand(); this random number generator will be used. , give the seed to the current time, that is, srand((unsigned) time (&t)); The random number function commonly used in my C language is as follows:

    C language random number

    #include <stdio.h>
    
    int main(void) {
    
    	int left,right;
    	printf("请输入一个数:");
    	scanf_s("%d%d",&left,&right);
    	//srand((unsigned)time(NULL));
    	//for(int i = 0; i<10; i++)
    	//printf("%d\n",rand() % one);
    	
    
    	//改进
    	for (int i = 0; i < 10; i++)
    	printf("随机值如下:%d\n", srandNext(left, right));
    
    	return 0;
    }
    
    /********************************************************************************
    * @Function: srandNext
    * @Description:Find a random integer from min to max
    * @Author: caiziqi
    * @Version: 1.1
    * @formal parameter:min : is the minimum value of the value range of this random number function, max: is the maximum value range of this random number function
    * @Date: 2022-7-26
    * @Return : returns a random integer
    ********************************************************************************/
    
    int srandNext(int max,int min) {
    
    	//To prevent users from passing parameters incorrectly
    	if (max <= min) {
    		if (max == min) {
    			return max;
    		}
    		int temp = max;
    		max = min;
    		min = temp;
    	}
    
    	unsigned int static seed = 0;
    	seed++;
    
    	srand((unsigned)time(NULL) + seed * seed);
    
    	return rand() % (max - min + 1) + min;
    }

    Of course this is not The most important thing today is to talk about the four methods of creating random numbers in Java that I learned

    java

    The following codes are all used to find a random integer between a ~ b

    1.Random

    Create object

    Random ra = new Random();
    int right = (Math.max(a,b)) ;
    int left = (Math.min(a,b);
    
    int nu = (ra.nextInt(right) + left );

    Value range left minimum value right maximum value

    2.SecureRandom

    Create object

    SecureRandom sra = new SecureRandom();
    int right = (Math.max(a,b)) ;
    int left = (Math.min(a,b);
    
    int nu = (sra .nextInt(right) + left );

    Value range left minimum value right maximum value

    3.ThreadLocalRandom

    Create object

    ThreadLocalRandom tra = ThreadLocalRandom.current();

    Find the left value and right value of the random number

    int right = (Math.max(a,b)) ;
    int left = (Math.min(a,b);
    
    int nu = (tra .nextInt(right) + left );

    The value range is left, minimum value, right, maximum value

    4.Math.Random

    Since the methods in Math are static, you can directly use the class name and method name

    int number = (int)(a + Math.random()*(b-a+1)) //返回一个int类型的参数 所以用 int 接收

    Range a <= random number< (b -a 1)

    2 <= random number< (4 -2 1)

    Complete code

    import java.security.SecureRandom;
    import java.util.Random;
    import java.util.Scanner;
    import java.util.concurrent.ThreadLocalRandom;
    
    public class FourWaysOfRandomNumbers {
        public static void main(String[] args) {
            //用户输入两个数, 然后程序取这两个数里面的其中随机一个数
            Scanner input =  new Scanner(System.in);
            System.out.print("请输入两个数:");
            int a = input.nextInt();
            int b = input.nextInt();
    
            // 取值范围   left 最小值    right 最大值
            int right = Math.max(a,b);
            int left = Math.min(a,b);
            int nu;
    
            //四种生成随机数的方法
    
            //第一种
            Random ra = new Random();
                 while( true){
                nu =(ra.nextInt(right) + left ) ;
                System.out.println(nu);
    
                //找到最大随机整数 输出并结束
                if(nu == right) {
    
                    System.out.println(nu);
                    return;
                }
            }
    
            //第二种
    /*
            SecureRandom sra = new SecureRandom();
    
            while(true){
                nu =(sra.nextInt(right) + left ) ;
                System.out.println(nu);
    
                //找到最大随机整数 输出并结束
                if(nu == right) {
                    System.out.println(nu);
                    return;
                }
            }*/
    
    
            //第三种  在多线程的时候使用 是最佳的; 因为它会为每个线程都 使用不同的种子
           /* ThreadLocalRandom tra =  ThreadLocalRandom.current();
            while(true){
                nu =(tra.nextInt(right) + left ) ;
                System.out.println(nu);
    
                //找到最大随机整数 输出并结束
                if(nu == right) {
                    System.out.println(nu);
                    return;
                }
            }*/
    
          /*  //第四种
             int value = (int)(a + Math.random()*(b-a+1));
            System.out.println(value);
    */
    
    
        }
    
    }

    The above is the detailed content of What are the ways to create random numbers in Java?. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete