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

后端 未结 6 534
滥情空心
滥情空心 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:37

    You're almost there. Just add 1 to the result:

    int randomInt = (int)d + 1;
    

    This will "shift" your range to 1 - 100 instead of 0 - 99.

    0 讨论(0)
  • 2020-12-11 02:39

    or

    Random r = new Random();
    int randomInt = r.nextInt(100) + 1;
    
    0 讨论(0)
  • 2020-12-11 02:40

    Here is a clean and working way to do it, with range checks! Enjoy.

    public double randDouble(double bound1, double bound2) {
            //make sure bound2> bound1
            double min = Math.min(bound1, bound2);
            double max = Math.max(bound1, bound2);
            //math.random gives random number from 0 to 1
            return min + (Math.random() * (max - min));
        }
    

    //Later just call:

    randDouble(1,100)
    //example result:
    //56.736451234
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-11 02:52
        double random = Math.random();
    
        double x = random*100;
    
        int y = (int)x + 1; //Add 1 to change the range to 1 - 100 instead of 0 - 99
    
        System.out.println("Random Number :");
    
        System.out.println(y);
    
    0 讨论(0)
  • 2020-12-11 02:57

    I will write int number = 1 + (int) (Math.random() * 100);

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