生成 1 到 10 Java 之间的随机数

编程入门 行业动态 更新时间:2024-10-26 12:27:48
本文介绍了生成 1 到 10 Java 之间的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想用 Java 生成一个 1 到 10 之间的数字.

I want to generate a number between 1 and 10 in Java.

这是我尝试过的:

Random rn = new Random(); int answer = rn.nextInt(10) + 1;

有没有办法在调用nextInt方法时告诉括号()中放什么以及添加什么?

Is there a way to tell what to put in the parenthesis () when calling the nextInt method and what to add?

推荐答案

As 文档 说,此方法调用返回0(包含)和指定值(不包含)之间的伪随机、均匀分布的 int 值".这意味着在您的情况下,您将获得从 0 到 9 的数字.因此,通过在该数字上加 1,您已正确完成所有操作.

As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)". This means that you will get numbers from 0 to 9 in your case. So you've done everything correctly by adding one to that number.

一般来说,如果你需要生成从min到max(包括两者)的数字,你写

Generally speaking, if you need to generate numbers from min to max (including both), you write

random.nextInt(max - min + 1) + min

更多推荐

生成 1 到 10 Java 之间的随机数

本文发布于:2023-11-08 16:25:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569875.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!