回答

收藏

如何在 Java 中生成特定范围内的随机整数?

技术问答 技术问答 421 人阅读 | 0 人回复 | 2023-09-11

如何生成int特定范围内的随机值?& H, d( C1 t& h2 E! n
我尝试了以下方法,但都不起作用:
! m' Q/ m9 Z, L) q1 [尝试1:- {1 y7 ?& q& s$ V' J
randomNum = minimum   (int)(Math.random() * maximum);错误:randomNum可以大于maximum.
5 n# Z+ w  N! q! G) J. r6 S/ B尝试2:
' c: x& D; l& |- ?Random rn = new Random();int n = maximum - minimum   1;int i = rn.nextInt() % n;randomNum =  minimum   i;错误:randomNum可以小于minimum.  d' L# S" w4 g( L
                                                                # {: Z# T& S$ W: n, {3 ^# k
    解决方案:                                                               
8 @5 H5 T) E+ Z1 d3 p                                                                在Java 1.本操作的标准方法如下:- D% ^8 a% e0 P7 b, s" S# X
import java.util.concurrent.ThreadLocalRandom;// nextInt is normally exclusive of the top value,// so add 1 to make it inclusiveint randomNum = ThreadLocalRandom.current().nextInt(min,max   1);请参考相关 JavaDoc。这种方法的优点是不需要显式初始化java.util.Random例如,如果使用不当,可能会造成混乱和错误。
/ r- E  P& j8 [1 o/ W( J然而,相反,没有办法明确设置种子,因此在测试或保存游戏状态或类似情况下可能很难重现结果。在这些情况下,可以使用以下 Java 1.7 以前的技术。
% w( E4 P$ r. d; a9 v- {5 _" h在 Java 1.7 前,执行此操作的标准方法如下:3 R$ s' @% ?* n- u6 C
import java.util.Random;/** * Returns a pseudo-random number between min and max,inclusive. * The difference between min and max can be at most * Integer.MAX_VALUE - 1. * * @param min Minimum value * @param max Maximum value.  Must be greater than min. * @return Integer between min and max,inclusive. * @see java.util.Random#nextInt(int) */public static int randInt(int min,int max)      / NOTE: This will (intentionally) not run as written so that folks    // copy-pasting have to think about how to initialize their    // Random instance.  Initialization of the Random instance is outside    // the main scope of the question,but some decent options are to have    // a field that is initialized once and then re-used as needed or to    // use ThreadLocalRandom (if using at least Java 1.7).    //     // In particular,do NOT do 'Random rand = new Random()' here or you    // will get not very good / not very random results.    Random rand;    // nextInt is normally exclusive of the top value,   // so add 1 to make it inclusive    int randomNum = rand.nextInt((max - min)  1)  min;    return randomNum;}请参考相关 JavaDoc。在实践中,java.util.Random类通常比java.lang.Math.random()更可取。
9 b" M9 o0 R* S& f4 @8 U特别是标准库中有一个简单的 API 完成任务时,无需重新发明随机整数生成轮。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则