• 如何用java生成指定范围的随机数


    以生成[10,20]随机数为例,首先生成0-20的随机数,然后对(20-10+1)取模得到[0-10]之间的随机数,然后加上min=10,最后生成的是10-20的随机数
     

    要生成在[min,max]之间的随机整数,

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    package edu.sjtu.erplab.io;
     
    import java.util.Random;
     
    public class RandomTest {
      public static void main(String[] args) {
        int max=20;
        int min=10;
        Random random = new Random();
     
        int s = random.nextInt(max)%(max-min+1) + min;
        System.out.println(s);
      }
    }

    random.nextInt(max)表示生成[0,max]之间的随机数,然后对(max-min+1)取模。

    以生成[10,20]随机数为例,首先生成0-20的随机数,然后对(20-10+1)取模得到[0-10]之间的随机数,然后加上min=10,最后生成的是10-20的随机数

    生成0-2之间的随机数,包括2

    1
    2
    Random rand = new Random();
    int randNum = rand.nextInt(3);

    生成5-26之间的随机数,包括26

    1
    int randNum = rand.nextInt(22)+5;

    工作当中许多地方会遇到,需要获取某指定范围内的随机数。直接利用Java给的的API中的函数不能满足,需要做些改变。

    实例:产生10个指定范围内的随机数。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    public class RandomTest {
      public static void main(String[] args) {
        int max = 10;
        int min = 2;
        //生成10个指定范围的随机数
        Random random = new Random();
        for(int i=0; i<10; i++){
          int n = random.nextInt(max-min+1)+min;
          System.out.print(n+" ");
        }
        System.out.println();
        for(int i=0; i<10; i++){
          int n = (int)(Math.random()*(max-min+1)+min);
          System.out.print(n+" ");
        }
      }
    }

    要生成在[min,max]之间的随机整数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    import java.util.Random;
    public class RandomTest {
      public static void main(String[] args) {
        int min=10;
        int max=20;
        Random random = new Random();
     
        //int s = random.nextInt(max)%(max-min+1) + min;
         int s = random.nextInt(max-min+1) + min;
     
        System.out.println(s);
      }
    }
  • 相关阅读:
    线程生命周期
    java集合源码分析几篇文章
    Java中的equals和hashCode方法详解
    java集合(一)
    volatile和synchronized实现内存可见性的区别
    动态代理的原理
    过滤器的使用
    pageBean的实体类
    FindUserByPageServlet
    用户信息系统_serviceImpl
  • 原文地址:https://www.cnblogs.com/javalinux/p/16255540.html
Copyright © 2020-2023  润新知