The best you can do with Random is still nextInt() as shown in Sasang's answer. Math.random () //Generate number between 0-9 int index (int) (Math.random ()10) Note 1. Random () //Generate number between 0-9 Random random new Random () int index random.nextInt (10) 3. Side remark: it's normal that it usually takes more than 8 million tries: while nextFloat() generates 24 bits, which is reduced to ~23 by throwing away almost half of the numbers, the generator itself works on 48 bits. ThreadLocalRandom (JDK 1.7) //Generate number between 0-9 int index ThreadLocalRandom.current ().nextInt (10) 2. ![]() Will typically show a couple ten million tries to generate both a 0 and 1, completes in less than a second for me on a 5-year old laptop. and then you can change the result to any format as suggeted by Zach Janicki. In order to modify this to a range between the integers. Throw new RuntimeException(current+">"+max) According to the actual calculation, 500/1500 will give you 0.33333 but compiler will convert this into integer literal because both operands are of type int (double)(0) Compiler gets an instruction to cast this 0 value to double so you got 0.0 as result. The method, Math.random(), will return a random value between 0 (inclusively) and 1.0 (exclusively). Example:- If we want to generate a number between 1 to 100 using the Math. Or a longer one with your actual numbers and some extra checks long start=System.currentTimeMillis() By default Math.random () always generates numbers between 0.0 to 1.0, but if we want to get numbers within a specific range then we have to multiply the return value by the magnitude of the range. Lets assume we want to generate a random integer between 0 and 10, can we do this Yes In java, we can get a specific range of values using the Math.random(). Method Summary Methods inherited from class java.lang. ![]() This function will generate random floats between 0 and 1, both ends included.Ī test snippet like long start=System.currentTimeMillis() Creates a new random number generator using a single long seed. ![]() If you can live with float and with ~8 million steps, you can simply throw away almost half of the numbers (one less than half of the numbers): private static Random rnd=new Random() To generate a 6-digit number: Use Random and nextInt as follows: Random rnd new Random () int n 100000 + rnd.nextInt (900000) Note that n will never be 7 digits (1000000) since nextInt (900000) can at most return 899999.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |