gettting a random number from 100 to 999

This question already has an answer here:

  • How do I generate random integers within a specific range in Java? 57 answers

  • There's a better way to get random numbers, and that's with java.util.Random . Math.random() returns a double (floating-point) value, but based on your request of a 3-digit number, I'm going to assume that what you really want is an integer. So here's what you do.

    // initialize a Random object somewhere; you should only need one
    Random random = new Random();
    
    // generate a random integer from 0 to 899, then add 100
    int x = random.nextInt(900) + 100;
    

    Math.random() returns value between 0.0 (including) and 1.0 (excluding) say it returns 0.05013371.. (for example) than your method will do the following operation,

    0.05013371.. * 100000 = 5013.371...
    (int) 5013.371... = 5013
    5013 % 1000 = 13 // Incorrect
    

    But other way around you can still use Math.random() in a different way to solve this,

    int upperBound = 999;
    int lowerBound = 100;
    int number = lowerBound + (int)(Math.random() * ((upperBound - lowerBound) + 1));
    

    Explanation,

    100 + (int)((Number >= 0.0 and  < 1.0) * (999 - 100)) + 1;
    100 + (int)((Number >= 0.0 and  < 1.0) * (899)) + 1;
    

    MIN This can return,

    100 + (int)(0.0 * (899)) + 1;
    100 + 0 + 1
    101
    

    MAX This can return,

    100 + (int)(0.9999.. * (899)) + 1;
    100 + 898 + 1 
    999
    

    NOTE : You can change upper and lower bound accordingly to get required results.


    You are not correct. That can produce numbers under 100 . The most familiar way is random.nextInt(900)+100 . Here random is an instance of Random .

    Before Java 7 there was no reason to create more than one instance of Random in your application for this purpose. Now there's no reason to have any, as the best way is

    int value = ThreadLocalRandom.current().nextInt(100, 1000);
    
    链接地址: http://www.djcxy.com/p/17678.html

    上一篇: Java中的Base64编码

    下一篇: 得到一个从100到999的随机数