views:

471

answers:

3

What method returns a random int between a min and max? Or does no such method exist?

what i'm looking for is something like this:

NAMEOFMETHOD (min, max) 

(where min and max are ints)

that returns soemthing like this:

8

(randomly)

if such a method does exist could you please link to the relevant documentation with your answer. thanks.

Update: atempting to implement the full solution in the nextInt answer i have this:

class TestR
{
    public static void main (String[]arg) 
    {   
        Random random = new Random() ;
        int randomNumber = random.nextInt(5) + 2;
        System.out.println (randomNumber) ; 
    } 
} 

i'm still getting the same errors from the complier:

TestR.java:5: cannot find symbol
symbol  : class Random
location: class TestR
        Random random = new Random() ;
        ^
TestR.java:5: cannot find symbol
symbol  : class Random
location: class TestR
        Random random = new Random() ;
                            ^
TestR.java:6: operator + cannot be applied to Random.nextInt,int
        int randomNumber = random.nextInt(5) + 2;
                                         ^
TestR.java:6: incompatible types
found   : <nulltype>
required: int
        int randomNumber = random.nextInt(5) + 2;
                                             ^
4 errors

whats going wrong here?

+5  A: 

Construct a Random object at application startup:

Random random = new Random();

Then use Random.nextInt(int):

int randomNumber = random.nextInt(max - min) + min;

Note that the lower limit is inclusive, but the upper limit is exclusive.

Mark Byers
i updated the question with the error that occurs when i try to do that what is going wrong?
David
David, you need to instantiate it first. `Random random = new Random();` It's still *just* Java code. There's no means of magic ;)
BalusC
And make sure that you only instantiate the Random object once and reuse it. Don't create a new Random object for each call to your function.
Mark Byers
Yes, you can safely make it a `static` variable of the class as well.
BalusC
i'm still not entirly clear on what you want me to do.
David
could you edit yoru answer to show the whole thing put together?
David
OK, I've updated my answer. If you need more help, I suggest you read an article or tutorial about random numbers in Java, such as this one: http://www.cs.geneseo.edu/~baldwin/reference/random.html
Mark Byers
i tried your answer so far as i can tell (updated OP) and it didnt' work. what did i do wrong?
David
You are missing `import java.util.Random;`.
Mark Byers
+2  A: 

You can use Random.nextInt(n). This returns a random int in [0,n). Just using max-min+1 in place of n and adding min to the answer will give a value in the desired range.

MAK
i updated the question with the error that occurs when i try to do that what is going wrong?
David
+1  A: 

import java.util.Random;

darlinton