View Full Version : Integer Arrays
Teddy Short
10-11-2006, 01:54 PM
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?
nelis
10-11-2006, 03:50 PM
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);
mwinter
10-11-2006, 05:29 PM
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);
nelis
10-11-2006, 06:10 PM
Whoops.. lmao.. didn't catch the forum section.
My bad..
:eek:
hey I had the right idea wrong syntax.. :)
Powered by vBulletin® Version 4.2.2 Copyright © 2023 vBulletin Solutions, Inc. All rights reserved.