我正在尝试生成存储的随机数,我需要返回字符串值。
这是我的方法:
public String generateRand() {
java.util.Random rand = new java.util.Random(System.currentTimeMillis());
String rnd = "" + Math.abs(rand.nextInt()) + "" +
Math.abs(System.currentTimeMillis());
return rnd;
}
Jenkins 的 Findbugs 插件警告我有Bad attempt to compute absolute value of signed random integer
。
此代码生成一个随机有符号整数,然后计算该随机整数的绝对值。如果随机数生成器返回的数字是 Integer.MIN_VALUE
,则结果也将为负,因为 Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE
。
长值也出现了同样的问题。
计算有符号随机整数的绝对值的最佳方法是什么?
最佳答案
使用
<code>rand.nextInt(Integer.MAX_VALUE);</code>
代替
<code>Math.abs(rand.nextInt())</code>
关于java - 如何计算有符号随机整数的绝对值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23435875/