search
HomeJavajavaTutorialWhat are the ways to create random numbers in Java?

    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

    2

    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:亿速云. If there is any infringement, please contact admin@php.cn delete
    How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

    The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

    How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

    The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

    How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

    The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

    How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

    The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

    How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

    Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

    See all articles

    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)
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Chat Commands and How to Use Them
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    SublimeText3 Linux new version

    SublimeText3 Linux new version

    SublimeText3 Linux latest version

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.