Results 1 to 2 of 2
  1. #1
    codeAJ's Avatar
    codeAJ is offline Member
    Join Date
    Mar 2011
    Posts
    23
    Rep Power
    0

    Default Math.random generating 0

    Hi all,

    I have create the following code in the hope of producing four random numbers from 1 to 6.

    Sometimes a '0' is returned, but I can't figure out why! :o

    Java Code:
    for (int i = 1; i <= 4; i++ ) {
       int num = (int)(Math.random() * (1 + 6));
       System.out.print(num);
    }

    Can someone please help me?

    Many thanks!

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Math.random returns a number from 0.0 to less than 1.0, which means there is more than a ten percent chance that a number smaller than 0.142 (approximately a 14.2% chance, obviously) and that number times 7 (why you do 1+6 there I don't know) is still less than 1.0 and casting a number smaller than 1 to int will produce 0.

    Edit: Use the Random class and "nextInt(6) + 1"

Similar Threads

  1. Generating random numbers
    By chinedum in forum New To Java
    Replies: 9
    Last Post: 09-21-2011, 05:03 AM
  2. generating double random number between 0 and 1
    By sara12345 in forum New To Java
    Replies: 6
    Last Post: 04-17-2010, 08:04 PM
  3. generating random number between 0 and 1
    By sara12345 in forum New To Java
    Replies: 1
    Last Post: 04-17-2010, 07:54 PM
  4. Generating a random number
    By oridov in forum New To Java
    Replies: 2
    Last Post: 11-29-2008, 05:12 PM
  5. generating random numbers in a 5x5 array.
    By acidacid in forum New To Java
    Replies: 3
    Last Post: 08-14-2007, 03:44 AM

Posting Permissions

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