java生成5随机数

一:

package com.urit.entity;

import java.util.*;
public class rd {
    public static void main(String[] args) {
        Set<Integer> set = new HashSet<>();
        while(set.size()<5){
            set.add(new Random().nextInt(33)+1);
        }
        System.out.println(set);
    }
}

二:

package com.urit.entity;
import java.util.Random;
public class random {
        public static void main(String[] args){
            Random rand = new Random();
            for(int i=0; i<5; i++) {
                System.out.println(rand.nextInt(33) + 1);
            }
        }
    }
Java 中,有多种方式可以生成随机数,以下为几种常见方法: 1. **使用 `Random` 类**:可以生成从 0 到指定范围的随机整数。以下是生成 0 到 10(不包含 10)的随机数示例代码: ```java import java.util.Random; public class RandomExample { public static void main(String[] args) { Random random = new Random(); for (int i = 0; i < 10; i++) { int number = random.nextInt(10); System.out.println("生成随机数:" + number); } } } ``` 这里使用 `Random` 类的 `nextInt` 方法生成随机数,`nextInt(10)` 会返回一个 0(包含)到 10(不包含)之间的随机整数 [^1]。 2. **使用 `Math.random()` 方法**:借助 `java.util.Math.random` 类方法提供了生成 `Double` 随机数的方法,其内部实现调用了 `java.util.Random` 的 `nextDouble` 方法,且对多线程有更好支持。返回的数值是 `[0.0, 1.0)` 的 `double` 型数值,可通过 `(int)` 进行类型转换得到整数随机数。示例代码如下: ```java public class MathRandomExample { public static void main(String[] args) { for (int i = 0; i < 10; i++) { int number = (int) (Math.random() * 10); System.out.println("生成随机数:" + number); } } } ``` 这里 `Math.random()` 生成一个 `[0.0, 1.0)` 之间的随机 `double` 数,乘以 10 后再转换为 `int` 类型,就得到了 0 到 9 之间的随机整数 [^2]。 3. **使用 `ThreadLocalRandom` 类**:适用于多线程环境,每个线程都有自己独立的随机数生成器,避免了多线程竞争问题。以下是生成 0 到 10(不包含 10)的随机数示例代码: ```java import java.util.concurrent.ThreadLocalRandom; public class ThreadLocalRandomExample { public static void main(String[] args) { ThreadLocalRandom random = ThreadLocalRandom.current(); for (int i = 0; i < 10; i++) { int number = random.nextInt(10); System.out.println("生成随机数:" + number); } } } ``` 使用 `ThreadLocalRandom.current()` 获取当前线程的随机数生成器,`nextInt(10)` 会返回一个 0(包含)到 10(不包含)之间的随机整数 [^3]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

启橙小屋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值