回答

收藏

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

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

如何生成int特定范围内的随机值?
' d: ~! G# }) c6 P1 k* g% F我尝试了以下方法,但都不起作用:5 G' d# h, u! w' _- {9 n9 r
尝试1:
# L! o# R$ G2 K6 L& [7 S7 \randomNum = minimum   (int)(Math.random() * maximum);错误:randomNum可以大于maximum.
! I+ E* b- Z9 O1 ?: P尝试2:
2 o: D6 w: D! ^Random rn = new Random();int n = maximum - minimum   1;int i = rn.nextInt() % n;randomNum =  minimum   i;错误:randomNum可以小于minimum.
. G$ T5 P# A8 V" x. p                                                                1 y9 k( C6 ]: _
    解决方案:                                                                2 C) P* d) s* P% d, X* D
                                                                在Java 1.本操作的标准方法如下:
: ^( I- r. }. \( ^: Z8 X3 Z; S$ Vimport 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例如,如果使用不当,可能会造成混乱和错误。! v9 e! r$ |) m" i6 k' j! ?
然而,相反,没有办法明确设置种子,因此在测试或保存游戏状态或类似情况下可能很难重现结果。在这些情况下,可以使用以下 Java 1.7 以前的技术。0 s) ~- M4 E! F) E
在 Java 1.7 前,执行此操作的标准方法如下:+ ~2 b' C6 y3 R. P0 t  V% ]1 j
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()更可取。
+ m/ j: |+ f0 D7 Q- m) s特别是标准库中有一个简单的 API 完成任务时,无需重新发明随机整数生成轮。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则