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

编程入门 行业动态 更新时间:2024-10-27 12:32:36
本文介绍了生成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 文档说,此方法调用返回伪随机,均匀分布的int值介于0(包括)和指定值(不包括)之间。这意味着在您的情况下,您将获得0到9之间的数字。所以你已经通过在该数字上加一个来正确地完成了所有事情。

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-10-28 23:05:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538026.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数   Java

发布评论

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

>www.elefans.com

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