Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute absolute value of signed random integer

Tags:

java

findbugs

I'm trying to generate the random number which is stored and I need to return the string value.

Here is My method:

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;
}

The Findbugs plugin of Jenkins is warning me that there is Bad attempt to compute absolute value of signed random integer.

This code generates a random signed integer and then computes the absolute value of that random integer. If the number returned by the random number generator is Integer.MIN_VALUE, then the result will be negative as well, since Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE. Same problem arised for long values as well.

What is the best way to to compute absolute value of signed random integer?

like image 655
Samarland Avatar asked May 02 '14 19:05

Samarland


1 Answers

Use rand.nextInt(Integer.MAX_VALUE); instead of Math.abs(rand.nextInt())

like image 126
luckman Avatar answered Oct 20 '22 17:10

luckman