Computer Science Canada

Randomint

Author:  magicman [ Mon Nov 08, 2004 1:46 pm ]
Post subject:  Randomint

I need some help on making a program that gives me a random
Int between 1-20 and 1-4.
thanx

Author:  wtd [ Mon Nov 08, 2004 3:35 pm ]
Post subject: 

Look in the Turing Tutorials forum. There's plenty of material there on how to generate random integers.

Author:  Hikaru79 [ Mon Nov 08, 2004 6:01 pm ]
Post subject: 

Here's a quick method to do that. Learning to implement and call this method is up to you =)

code:

public static int randInt (int minBound, int maxBound)
{
int randomNumber;
randomNumber = (int) Math.round(Math.random()*(maxBound+1))+minBound;
return randomNumber;
}


Tested and true Very Happy

Author:  wtd [ Mon Nov 08, 2004 6:55 pm ]
Post subject: 

D'oh... got this one and Turing Help forum mxed up.

Author:  zylum [ Wed Nov 10, 2004 9:42 pm ]
Post subject: 

Hikaru79 wrote:
Here's a quick method to do that. Learning to implement and call this method is up to you =)

code:

public static int randInt (int minBound, int maxBound)
{
int randomNumber;
randomNumber = (int) Math.round(Math.random()*(maxBound+1))+minBound;
return randomNumber;
}


Tested and true Very Happy


that wont work, it should be:

Math.floor(Math.random()*(maxBound-minbound+1))+minBound;

Author:  Hikaru79 [ Wed Nov 10, 2004 10:59 pm ]
Post subject: 

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:

code:
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


: