Helpful Information
 
 
Category: Java
Integer Arrays

Hey does anyone know a for loop code that will enable me to assign a 50 array integer (the coding for this is "int[] myArray = new int[50];") with a random number between 1 to 1000. Im guessing it does need to be a for loop to be able to make it randomised?

I think you want something like this:

var myArray = new Array(50);

for(var i=0;i<myArray.length;i++)
{
myArray[i]=Math.round(1000*Math.random());
}

nelis: This is the Java forum.
int[] myArray = new int[50];

for(int i = 0; i < myArray.length; ++i)
myArray[i] = Math.floor(Math.random() * 1000 + 1);

nelis: This is the Java forum.

Heh. I almost made the same mistake. :)



myArray[i] = Math.floor(Math.random() * 1000 + 1);

You didn't truncate the result: the floor method returns a double, and assigning to type int will generate an error.

Mike

Oh yes. Heh, too much implicit casting.
int[] myArray = new int[50];

for(int i = 0; i < myArray.length; ++i)
myArray[i] = (int)Math.floor(Math.random() * 1000 + 1);

Whoops.. lmao.. didn't catch the forum section.

My bad..
:eek:


hey I had the right idea wrong syntax.. :)










privacy (GDPR)