简体   繁体   中英

Java Math.Random() for series of numbers

是否可以在Java中使用Math.Random()获得一系列数字,例如10、20、30、40 ...或100、200、300。...我当前的实现是Math.Random()* 3 * 100,因为我认为这将带给我最多300个可被100整除的数字。

This code returns a random number with step 10. 0 is excluded from this, but if you want to add it, take out the +1 on the Math.random() line.

int step = 10;
int random = (int)(Math.random()*10+1)*step; //10 is the number of possible outcomes
System.out.println("Random with step " + step + ":" random);

Math.random() returns a double . You want an int value, so you should use the Random class. You should probably do that anyway.

Random rnd = new Random();
int num = (rnd.nextInt(30) + 1) * 10; // 10, 20, 30, ..., 300

Explanation:

nextInt(30) returns a random number between 0 and 29 (inclusive).
+ 1 then makes that a number between 1 and 30.
* 10 then makes that 10, 20, 30, ..., 300 .

So, if you just want 100, 200, 300 , use:

int num = (rnd.nextInt(3) + 1) * 100; // 100, 200, 300

The documentation of Math.random() states that a call returns a

double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

This means, the resulting number of your computation is between 0 and 300, but it is not of type int , but of type double . You should add a call to Math.round or simply cast it to int and add a loop if you want to create multiple values..

If you wanted to return numbers such as 10, 20, 30, 40, 50, 60... the following should do this.

int ranNumber=(int)(Math.random()*10+1)*10;
System.out.println(ranNumber);

//sample output: 80

There doesn't seem to be a direct way to do that but i'm sure with some manipulation we can do it. Below i have created the method randSeries to generate a number based off of a series. You send this method two values, a increment, which is how big you want the base of your series number to be. Then the base, which is your 10s, 20s, 30s. We are essentially generating a random number in the range you provide the method, then multiplying it by the base you sent the method to create a value that is divisible by your base.

    public int randSeries(int increment, int base){
        Random rand = new Random();

        int range = rand.nextInt(increment)+1; //random number
        System.out.println(range);

        int finalVal = range * base; //turning your random number into a series
        System.out.println(finalVal);

        return finalVal; //return
    }

As a note :: This method can be used to generate numbers of ANY base value not just 10.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM