Last active
February 1, 2016 02:55
-
-
Save wutianlong/2b1f95392f7de82208fa to your computer and use it in GitHub Desktop.
高效率生成随机数字
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
我试着使用Java生成一个随机整数,但是随机被指定在一个范围里。例如,整数范围是5~10,就是说5是最小的随机值,10是最大的。5到10之间的书也可以是生成的随机数。 | |
解决方案 | |
标准的解决方式(Java1.7 之前)如下: | |
import java.util.Random; | |
public static int randInt(int min, int max) { | |
Random rand; | |
int randomNum = rand.nextInt((max - min) + 1) + min; | |
return randomNum; | |
} | |
请查看相关的JavaDoc。在实践中,java.util.Random 类总是优于 java.lang.Math.random()。 | |
特别是当标准库里有一个直接的API来完成这个工作,就没有必要重复制造轮子了。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment