java之生成随机数的方式1:Random.nextInt()

本文详细介绍了Java中使用java.util.Random类的nextInt()方法生成随机数的方法,包括无参和有参构造器的使用,以及nextInt()和nextInt(int)两个方法的区别。通过实例代码展示了不同构造方式和方法调用如何影响随机数生成,强调了random.nextInt(10)是决定生成[0, 9]范围内随机数的关键。" 126214486,15028472,HTML5个人网页设计与实现:从零开始制作校园网站,"['HTML静态网页作业', 'web前端开发技术', '网页规划与设计', 'HTML5期末考核大作业', '个人网页设计与实现']

java中生成随机数的方式之1:

利用 java.util.Random 工具类可以生成随机数,以jdk1.8为例

 

1、Random对象的创建

     我们先来看下Random的构造方法

// 无参构造
public Random(){}

// 带参构造
public Random(long seed){}

  我们来看一下它的相关源码:

    /** 
     * Creates a new random number generator. This constructor sets
     * the seed of the random number generator to a value very likely
     * to be distinct from any other invocation of this constructor.
     */
    public Random() {
        this(seedUniquifier() ^ System.nanoTime());
    }

    /**
     * Creates a new random number generator using a single {@code long} seed.
     * The seed is the initial value of the internal state of the pseudorandom
     * number generator which is maintained by method {@link #next}.
     *
     * <p>The invocation {@code new Random(seed)} is equivalent to:
     *  <pre> {@code
     * Random rnd = new Random();
     * rnd.setSeed(seed);}</pre>
     *
     * @param seed the initial seed
     * @see   #setSeed(long)
     */
    public Random(long seed) {
        if (getClass() == Random.class)
            this.seed = new AtomicLong(initialScramble(seed));
        else {
            // subclass might have overriden setSeed
            this.seed = new AtomicLong();
            setSeed(seed);
        }
    }

 从源码中我们可以获取的信息有:

对于无参构造方法,

Random() 在创建对象时,会生成一个随机数作为种子,利用这个种子生成新的随机数。而这个随机数是当前系统时间的纳秒值和另外一个长整型毫秒值的异或运算的结果【this(seedUniquifier() ^ System.nanoTime())

对于有参构造方法,

根据方法上的注释,我们发现 

方式1:

Random rd1 = new Random(10);

等价于以下语法

方式2:

Random rd2 = new Random();

rd.nextInt(10);

但是,实际测试中,并没有这么简单,请参照第3标题下的内容。

2、Random对象的生成随机数的相关方法

Random类中,生成随机整数的相关方法有:

    /**
     * ...
     * @return the next pseudorandom, uniformly distributed {@code int}
     *         value from this random number generator's sequence
     */
    public int nextInt() {
        return next(32);
    }

    /**
     * ...
     * @param bound the upper bound (exclusive).  Must be positive.
     * @return the next pseudorandom, uniformly distributed {@code int}
     *         value between zero (inclusive) and {@code bound} (exclusive)
     *         from this random number generator's sequence
     * @throws IllegalArgumentException if bound is not positive
     * @since 1.2
     */
    public int nextInt(int bound) {
        if (bound <= 0)
            throw new IllegalArgumentException(BadBound);

        int r = next(31);
        int m = bound - 1;
        if ((bound & m) == 0)  // i.e., bound is a power of 2
            r = (int)((bound * (long)r) >> 31);
        else {
            for (int u = r;
                 u - (r = u % bound) + m < 0;
                 u = next(31))
                ;
        }
        return r;
    }

nextInt() 和 nextInt(int) 这两个方法都可以用来生成随机数。

但是它们两个方法的区别在于

   假设 Random ra = new Random();

   ra.nextInt()     会生成一个任意的 随机整数(包括正数和负数)

   ra.nextInt(int)  会生成一个 [0,9] 之间的任意一个整数

测试代码如下:

public class TestRandomConstructor {
	public static void main(String[] args) {
		System.out.println("========================= nextInt(10) ================");
		Random rd1 = new Random();
		for (int i = 0; i < 20; i++) {
			System.out.println(rd1.nextInt(10));
		}
		System.out.println("========================= nextInt() ================");
		for (int i = 0; i < 20; i++) {
			System.out.println(rd1.nextInt());
		}
	}
}

测试结果:

========================= nextInt(10) ================
7
7
8
1
8
2
7
6
1
0
...
========================= nextInt() ================
439364996
1142968751
-1245259674
-896549010
-1870260620
1931734780
1153394322
-1781928093
....

3、其他知识点

假设   Random ra = new Random(10);

测试代码:

public class TestRandomConstructor {
	public static void main(String[] args) {
		System.out.println("========================= nextInt(10) ================");
		Random rd1 = new Random(10);
		for (int i = 0; i < 20; i++) {
			System.out.println(rd1.nextInt(10));
		}
		System.out.println("========================= nextInt() ================");
		for (int i = 0; i < 20; i++) {
			System.out.println(rd1.nextInt());
		}
	}
}

测试结果:

========================= nextInt(10) ================
3
0
3
0
6
6
7
8
1
4
3
8
......
========================= nextInt() ================
35545786
-347474078
1892459190
498897016
134578271
-1339421797
-331953347
772426541
1684007666
......

    所以,最终我们可以得出结论,决定最后生成的随机数的是 random.nextInt(10)

    而不是 Random ra = new Random(10); 

 

此文希望可以帮助到大家。如有错误,请指教。                                                           

如果大家还有其他的情况或者好的解决方法,也望指教,感谢阅读。

### 使用 Gin 框架实现 CRUD(增删改查)操作 #### 创建项目结构并初始化依赖项 为了使用 GinGORM 来处理 CRUD 操作,首先需要设置好 Go 项目的环境。安装必要的包: ```bash go mod init example.com/gin-crud-demo go get -u github.com/gin-gonic/gin go get -u gorm.io/gorm go get -u gorm.io/driver/sqlite ``` #### 定义数据模型 定义 `Product` 结构体作为数据库中的表模型[^2]。 ```go type Product struct { gorm.Model Code string Price uint } ``` #### 初始化数据库连接 建立与 SQLite 数据库的连接,并自动迁移模式以创建相应的表格。 ```go import ( "gorm.io/driver/sqlite" "gorm.io/gorm" ) func InitDB() *gorm.DB { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } // 自动迁移模式 db.AutoMigrate(&Product{}) return db } ``` #### 设置路由和控制器逻辑 编写 HTTP API 路由以及对应的业务逻辑函数来完成 CRUD 功能。 ```go package main import ( "net/http" "github.com/gin-gonic/gin" ) var DB = InitDB() // 获取所有产品列表 func GetProducts(c *gin.Context) { var products []Product result := DB.Find(&products) if result.Error != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": result.Error}) return } c.JSON(http.StatusOK, products) } // 添加新产品 func CreateProduct(c *gin.Context) { var input Product if err := c.ShouldBindJSON(&input); err == nil { createErr := DB.Create(&input).Error if createErr != nil { c.JSON(http.StatusBadRequest, gin.H{"error": createErr}) return } c.JSON(http.StatusOK, input) } else { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } } // 更新指定ID的产品信息 func UpdateProduct(c *gin.Context) { id := c.Params.ByName("id") var product Product if err := DB.Where("id = ?", id).First(&product).Error; err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"}) return } updateErr := DB.Model(&product).Updates(Product{Code: c.PostForm("code"), Price: c.PostFormUint("price")}).Error if updateErr != nil { c.JSON(http.StatusBadRequest, gin.H{"error": updateErr}) return } c.JSON(http.StatusOK, product) } // 删除指定ID的产品记录 func DeleteProduct(c *gin.Context) { id := c.Params.ByName("id") var product Product d := DB.Delete(&product, id) if d.Error != nil { c.JSON(http.StatusBadRequest, gin.H{"error": d.Error}) return } c.JSON(http.StatusOK, gin.H{"id #" + id: "deleted"}) } func SetupRouter() *gin.Engine { r := gin.Default() apiV1 := r.Group("/api/v1") { apiV1.GET("/products", GetProducts) apiV1.POST("/products", CreateProduct) apiV1.PUT("/products/:id", UpdateProduct) apiV1.DELETE("/products/:id", DeleteProduct) } return r } func main() { router := SetupRouter() router.Run(":8080") } ``` 此代码片段展示了如何利用 Gin 框架配合 GORM ORM 库执行基本的数据持久化任务——即所谓的 CRUD 操作。每种操作都对应着 RESTful 风格下的不同 URL 地址及其请求方法[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值