3
I cannot generate a random number that is negative, for example less than 0
6
import java.util.Random;
Random rand = new Random();
int n = (rand.nextInt(50) + 1) * -1;
The above example is purely didactic.
The number 50 defines the range and has been set for demonstration purposes. A random number between 0 and 49 will be generated. So we add +1 so that the numbers are between 1 and 50.
The result obtained is multiplied by -1 because in mathematics a positive number multiplied by a negative number becomes negative. This we learn in school.
This gives the expected result. A random negative number.
There are obviously other ways to get the same result. The above example is merely illustrative. Doesn’t mean it’s the best or the only way.
Adapt the example to your needs.
Remembering that in JAVA we can also convert in a more summary way:
n = 10;
n = -n; // Resultado: -10
3
Generate a positive number and multiply it by -1;
2
Generate a positive number normally and then multiply by -1.
I messed up, I’ve edited and fixed.
Thanks for the correction. :-)
@Paulosantos who made confusion was not Marcio? Since he is the author of this answer?
Browser other questions tagged java random
You are not signed in. Login or sign up in order to post.
http://www.devmedia.com.br/numeros-aleatorios-em-java-a-classe-java-util-random/26355 generates a random number , multiply by -1.
– Motta
thanks, it worked out
– Vitor Martins
@Motta responds.
– Maniero
@Motta would be good to put as an official answer, if he could with a line of example. I think it’s more appropriate to make your solution positive and close the matter, so Vitor could mark yours as resolved, since you’re the one who actually solved it. And the example would help other visitors.
– Bacco
Daniel Omnine has done it @Bacco.
– Motta
@Motta didn’t have his when I mentioned it. It really would have been better yours as a matter of ethics, however if you had a lean and objective alternative, count on my vote.
– Bacco
Always remembering that in general the functions of type "Random" generate a pseudo-random number that in some applications are not recommended.
– Motta