Results 1 to 5 of 5

Thread: Random number

  1. #1
    _Chip is offline Member
    Join Date
    Nov 2012
    Posts
    1
    Rep Power
    0

    Default Random number

    Hello.
    Im new to java and I have a small question, couldn't find answer to it.

    How I can create a random number between -1000 and 1000 for example.
    I guess it's possible to do it with Math.random() function, but how?

    Thanks in advance.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,305
    Blog Entries
    7
    Rep Power
    20

    Default Re: Random number

    Quote Originally Posted by _Chip View Post
    Hello.
    Im new to java and I have a small question, couldn't find answer to it.

    How I can create a random number between -1000 and 1000 for example.
    I guess it's possible to do it with Math.random() function, but how?

    Thanks in advance.
    Also have a look at the Random class; note that if you can generate a pseudo random number in the interval [0 ... n) you can also generate a pseudo random number in the range [-m ... n-m) (simply subtract m from the first result).

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Random number

    You can use the Random class which has a method called nextInt(range) which returns a number from 0 to range - 1. Just use the appropriate range, and then subtract 1000 from the returned int.

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,305
    Blog Entries
    7
    Rep Power
    20

    Default Re: Random number

    Man, do I feel fast today.

    kind regards,

    Jos ;-)
    cenosillicaphobia: the fear for an empty beer glass

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. Random number not gen. number 0???
    By Mr U in forum New To Java
    Replies: 2
    Last Post: 10-17-2012, 02:18 AM
  2. Help with my first program. Random number gen.
    By bobmiknob in forum New To Java
    Replies: 1
    Last Post: 09-25-2011, 12:43 AM
  3. Generating a random number
    By oridov in forum New To Java
    Replies: 2
    Last Post: 11-29-2008, 05:12 PM
  4. Random number help
    By jgonzalez14 in forum New To Java
    Replies: 5
    Last Post: 09-16-2008, 09:13 AM
  5. Random number
    By jithan in forum Advanced Java
    Replies: 1
    Last Post: 06-13-2008, 01:42 PM

Posting Permissions

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