java 生成特定范围内的随机数

 

1
2
3
4
5
6
7
/**
* 生成[1, max]之间的随机数
*/
public static Integer getRandomNumber(Integer max) {
    Random rd = new Random();
    return rd.nextInt(max) + 1;
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 生成[x, y]之间的随机数
 * @return [x, y]之间的随机数
 */
public static Integer getRandomNumber2() {
    Integer min = 200;
    Integer max = 500;
 
    Random random = new  Random();
 
    /**
     * random.nextInt(max) % (max-min+1)  ->  [0, 499] % 301 == [0, 300]
     * [0, 300] + 200 = [200, 500]
     */
    int result = random.nextInt(max) % (max-min+1) + min;
    return result;
}

  

posted @ 2018-08-31 10:50  裸奔的太阳  阅读(4116)  评论(0)    收藏  举报
编辑推荐:
· 记一次 C# 平台调用中因非托管 union 类型导致的内存访问越界
· [EF Core]聊聊“复合”属性
· 那些被推迟的 C# 14 特性及其背后的故事
· 我最喜欢的 C# 14 新特性
· 程序员究竟要不要写文章
阅读排行:
· 遭遇疯狂 cc 攻击的一个周末
· 美丽而脆弱的天体运动:当C#遇见宇宙混沌
· 【EF Core】聊聊“复合”属性
· C#/.NET/.NET Core技术前沿周刊 | 第 49 期(2025年8.1-8.10)
· GPT‑5 重磅发布
点击右上角即可分享
微信分享提示