Results 1 to 6 of 6

Thread: Integer Arrays

  1. #1
    Join Date
    Oct 2006
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default 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?

  2. #2
    Join Date
    Oct 2006
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    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());
    }

  3. #3
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,878
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    nelis: This is the Java forum.
    Code:
    int[] myArray = new int[50];
    
    for(int i = 0; i < myArray.length; ++i)
      myArray[i] = Math.floor(Math.random() * 1000 + 1);
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends franšais | entiendo espa˝ol | t˘i Ýt hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  4. #4
    Join Date
    Dec 2004
    Location
    UK
    Posts
    2,358
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by Twey
    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

  5. #5
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,878
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    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);
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends franšais | entiendo espa˝ol | t˘i Ýt hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  6. #6
    Join Date
    Oct 2006
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

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

    My bad..



    hey I had the right idea wrong syntax..

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •