We also have functions that generate a random value following a Gaussian curve or that fill an array with random bytes. nextInt ( 10 ) + 1 // Between 0 and 10 excluded, plus 1, that is, from 1 to 10 both included. Random r = new Random () int valorDado = r. In our example from 1 to 10, it would be (10-1)+1 = 10. If we wanted values between any two numbers both included, for example, from 5 to 10, the count would be (maximum-minimum)+1, that is, (10- 5)+1 = 6, we would multiply by 6. Then we must multiply Math.random() by 10. In our case, from 1 to 10, there are 10 values: from 1 to 10 both included. ![]() We must do some math to obtain what we want.įirst of all, we look at how many values we want. Another typical case is to generate a random number from 1 to 10. For example, if we want to simulate a dice roll, we want numbers between 1 and 6 without decimals. In many of our applications, this range of values is not what we want. The call to Math.random() returns a random number between 0.0 and 1.0, excluding this last value, that is, it can return 0.346442, 0.2344234, 0.98345. If any questions about the subject or java in general, I usually answer in the java forum. We will also see some interesting cases, for example, generating random numbers without repetition or generating a random characters sequence (a String). On the one hand, we can use Math.random(), and on the other the class. To generate random numbers in Java we have two options.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |