Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Randomint
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
magicman




PostPosted: 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
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Mon Nov 08, 2004 3:35 pm   Post subject: (No subject)

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




PostPosted: Mon Nov 08, 2004 6:01 pm   Post subject: (No 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
wtd




PostPosted: Mon Nov 08, 2004 6:55 pm   Post subject: (No subject)

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




PostPosted: Wed Nov 10, 2004 9:42 pm   Post subject: (No 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;
Hikaru79




PostPosted: Wed Nov 10, 2004 10:59 pm   Post subject: (No 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
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 6 Posts ]
Jump to:   


Style:  
Search: