TechArena Community Want an array of Random numbers

#1
03-11-2009
 Member Join Date: Nov 2009 Posts: 347
Want an array of Random numbers

I am learning java programming, and want to develop a small program code to help me with my other codes. I am looking to develop a program that will give me random numbers which i can assign to array which is of user-defined size. Would appreciate any help from the techies in here.
#2
03-11-2009
 Member Join Date: Jan 2008 Posts: 1,515
Re: Want an array of Random numbers

If you want to take the input array size from the user, you need to use the JOptionPane().
After you get the array size, make a new array of that size. Then what you need to do is use a loop to fill the array with random numbers, which can be generated by the Math.random(). Remember: Math.random() gives value between 0 and 1. For your purpose, you can multiply the above number by some number and floor it by the Math.floor() method. Like if you want the range from 0 to 10, multiply the random number by 10. In case you still face any problems, please feel free to post it

Last edited by Modifier : 03-11-2009 at 02:19 PM.
#3
03-11-2009
 Member Join Date: Nov 2009 Posts: 347
Re: Want an array of Random numbers

I do know how to use the JOPane() and will try that Math.random() and Math.floor(). I have one more question, how do i increase the lower level of the limit.? that is if the lower limit is 0 and i want it to be 5? Thanks a lot!

Last edited by InterNetWorKed : 03-11-2009 at 02:22 PM.
#4
03-11-2009
 Member Join Date: Nov 2009 Posts: 343
Re: Want an array of Random numbers

I am pretty new to Java. I was going through the post and I tried he Math.random() and Math.floor(), but i want to know what exactly does the Math.floor() method do..?? i mean i used it alright, but what does it do..???

Last edited by Windowed : 03-11-2009 at 02:20 PM.
#5
03-11-2009
 Member Join Date: Jan 2008 Posts: 1,515
Re: Want an array of Random numbers

InterNetWorKed Just add the number to the floored number like
Code:
`Math.floor(Math.random()*10)+5`
Windowed
Flooring means rounding up.. like when u get a random number, it will be between 0 and1, and when you multiply it with some number it can result in a decimal number, but what is required is an integer.So the Math.floor() is used. remember: Math.floor() rounds just removes the decimals.. that is if number is 2.1 it will be rounded to 2, also 2.9 will be rounded to 2 as it is being Floored.

 Tags: