as gender random numbers according to the ranges chosen by a user? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

as gender random numbers according to the ranges chosen by a user?

23rd Dec 2017, 3:31 AM
Anthony
2 Answers
+ 1
1/2-There are two ways you can do this. The first way is to use the Random class, which you must import at the very top of your class like you would any other import. import java.util.Random; Then, you instantiate a Random object, and create an integer using it. int x=10; Random rndm= new Random(); int number = rndm.nextInt(x); I should note here that inside the nextInt() argument is where you would insert the number at the maximum range you want your random number to be. For example, I chose 10, which means the random number will be 0≤x<10. So it is from 0 inclusive to the chose number but doesn't include it, and since we are working with integer, that would be x-1, or 9 If you chose 50, for example, you would get a number randomly from 0 to 49. You could, of course, add 1 to this value to manipulate it so that it is between 1 and 50, or modify it in other ways to achieve a goal.
23rd Dec 2017, 3:42 AM
Mohamed
Mohamed - avatar
+ 1
2/2-The second way you can do this is to use the Math class, via Math.random(). This method requires a little bit more work but you have more control over it. The way Math.random() works is it generates a random value from 0.0 to 0.999... . Let's say you wanted a random double from 0≤x<30, meaning 0 to 29.999..., you would do: double number = Math.random() * 30; If you wanted to cast this as an integer, you would do: int number = (int)(Math.random() * 30); This operates exactly like the Random class, it will generate a number from 0 to 29, because the decimal point gets truncated. You could also do: int number = (int)(Math.random() * 50 + 1); if you wanted a value from 1 to 50 instead. You have more control this way so it's fully up to you.
23rd Dec 2017, 3:51 AM
Mohamed
Mohamed - avatar