How to get a random between 1 - 100 from randDouble in Java?

后端 未结 6 550
滥情空心
滥情空心 2020-12-11 01:55

Okay, I\'m still fairly new to Java. We\'ve been given an assisgnment to create a game where you have to guess a random integer that the computer had generated. The problem

6条回答
  •  隐瞒了意图╮
    2020-12-11 02:43

    The ThreadLocalRandom class provides the int nextInt(int origin, int bound) method to get a random integer in a range:

    // Returns a random int between 1 (inclusive) & 101 (exclusive)
    int randomInt = ThreadLocalRandom.current().nextInt(1, 101)
    

    ThreadLocalRandom is one of several ways to generate random numbers in Java, including the older Math.random() method and java.util.Random class. The advantage of ThreadLocalRandom is that it is specifically designed be used within a single thread, avoiding the additional thread synchronization costs imposed by the other implementations. Therefore, it is usually the best built-in random implementation to use outside of a security-sensitive context.

    When applicable, use of ThreadLocalRandom rather than shared Random objects in concurrent programs will typically encounter much less overhead and contention.

提交回复
热议问题