A random number in the range from -10 to 10 in Java.


Friends, welcome!

It is necessary to generate a random number in the range from -10 to 10. nextInt() does not allow this. A similar question was asked, but I can not master what I wrote (I need the entire code).

Not so long ago I started learning Java, don't be strict. Thank you in advance!

Author: Дух сообщества, 2014-11-27

1 answers

Then, apparently, you need to throw away the book that you are studying from, if you can't write something like:

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        Random r = new Random(System.currentTimeMillis());
        for (int i = 0; i<1000;i++) {
            int q = r.nextInt(21) - 10;
            System.out.println(q);
        }
    }
}

And that's why there are 21 and 10-this is already a homework assignment.

Update

Random takes the seed parameter , which is a special parameter for generating a sequence. In many languages, the random function is made so that if the initial value is the same, then the sequence will be the same.

This is done for debugging purposes and determinism (that is, that everything is stable and repeatable) of programs.

But setting the current time as a seed (which is not repeated) makes it possible to generate different sequences.

 7
Author: KoVadim, 2014-11-28 14:36:06