
-----------------------------------
magicman
Mon Nov 08, 2004 1:46 pm

Randomint
-----------------------------------
I need some help on making a program that gives me a random 
Int between 1-20 and 1-4.
thanx

-----------------------------------
wtd
Mon Nov 08, 2004 3:35 pm


-----------------------------------
Look in the [url=http://www.compsci.ca/v2/viewforum.php?f=3]Turing Tutorials forum.  There's plenty of material there on how to generate random integers.

-----------------------------------
Hikaru79
Mon Nov 08, 2004 6:01 pm


-----------------------------------
Here's a quick method to do that. Learning to implement and call this method is up to you =)


public static int randInt (int minBound, int maxBound)
{
int randomNumber;
randomNumber = (int) Math.round(Math.random()*(maxBound+1))+minBound;
return randomNumber;
}


Tested and true :D

-----------------------------------
wtd
Mon Nov 08, 2004 6:55 pm


-----------------------------------
D'oh... got this one and Turing Help forum mxed up.

-----------------------------------
zylum
Wed Nov 10, 2004 9:42 pm


-----------------------------------
Here's a quick method to do that. Learning to implement and call this method is up to you =)


public static int randInt (int minBound, int maxBound)
{
int randomNumber;
randomNumber = (int) Math.round(Math.random()*(maxBound+1))+minBound;
return randomNumber;
}


Tested and true :D

that wont work, it should be:

Math.floor(Math.random()*(maxBound-minbound+1))+minBound;

-----------------------------------
Hikaru79
Wed Nov 10, 2004 10:59 pm


-----------------------------------
Ah, you're right. I see my mistake =)

Your code requires just a tiny bit of correction too, though. For one, you forgot to capitalize minBound in one of the cases. Also, it needs (int) in front of the assignment or else you get a compile error ("Possible loss of precision").

So, here's a final program:

public class RandInt
{
public static void main(String [] args)
{
System.out.println (randInt(10,15));
}

public static int randInt (int minBound, int maxBound)
{
int randomNumber;
randomNumber = (int) Math.floor(Math.random()*(maxBound-minBound+1))+minBound;
return randomNumber;
}

}

This will return a random number from minBound to maxBound which are 10 and 15 in this case.

Hope this helps =D
