如何在特定范围内生成随机int
值?
以下方法存在与整数溢出相关的错误:
randomNum = minimum + (int)(Math.random() * maximum);// Bug: `randomNum` can be bigger than `maximum`.
Random rn = new Random();int n = maximum - minimum + 1;int i = rn.nextInt() % n;randomNum = minimum + i;// Bug: `randomNum` can be smaller than `minimum`.