How do I generate a random integer between min and max in Java?

后端 未结 8 1242
醉酒成梦
醉酒成梦 2020-12-13 09:15

What method returns a random int between a min and max? Or does no such method exist?

What I\'m looking for is something like this:

NAMEOFMETHOD (mi         


        
相关标签:
8条回答
  • 2020-12-13 09:42

    This generates a random integer of size psize

    public static Integer getRandom(Integer pSize) {
    
        if(pSize<=0) {
            return null;
        }
        Double min_d = Math.pow(10, pSize.doubleValue()-1D);
        Double max_d = (Math.pow(10, (pSize).doubleValue()))-1D;
        int min = min_d.intValue();
        int max = max_d.intValue();
        return RAND.nextInt(max-min) + min;
    }
    
    0 讨论(0)
  • 2020-12-13 09:44

    You can use Random.nextInt(n). This returns a random int in [0,n). Just using max-min+1 in place of n and adding min to the answer will give a value in the desired range.

    0 讨论(0)
提交回复
热议问题