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

后端 未结 8 1243
醉酒成梦
醉酒成梦 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:40

    Using the Random class is the way to go as suggested in the accepted answer, but here is a less straight-forward correct way of doing it if you didn't want to create a new Random object :

    min + (int) (Math.random() * (max - min + 1));
    

提交回复
热议问题