Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to generate random numbers using Java?

Status
Not open for further replies.

blackbirdMIT

IS-IT--Management
Aug 28, 2003
22
US
I need help in generating random numbers using JAVA. I need to generate at least three sets of numbers (not duplicated). The set range should be between integers 1 to 55.

I need some code to start with as I'm new in this Java programming arena. The output is simply using System.out.print (...) and not applets.

Thanks in advance.
 

_____________________________________________________________________
onpnt2.gif

 
I need help!

Below is my code:

import java.util.*;

class RandomInts {

public static void main (String args[]) {
System.out.println ("You have generated quick pick Lottery numbers.\n" + "Goodluck! Here they are:\n");

int number = 0;
int limit = 6;

Random generator = new Random();
number = 1+(int) (49*Math.random()); // I'd like to get a random integer between 1 and 49


for (int i=0; i<limit; i++) // repeat from 1 to the value of limit. repeat six times in this case.

System.out.println (generator.nextInt()%49);

} // end main method
} // end class

My problems:
1) I get zero in my random numbers
2) I get duplicate numbers in my set of six numbers

My major problem:
I'm stuck now. I don't know how to create at least five sets of six numbers.

Thank you in advance for your guidance.
 
sr727

i got the below output by compiling your code, with the exception of the &quot;number from math.random&quot;. it seems like problem1 and 2 do not exist. for 5 sets of 6 numbers, use 2 &quot;for loop&quot;

=================================================
You have generated quick pick Lottery numbers.
Goodluck! Here they are:

number from math.random is 14
14
-1
40
-21
24
34
 
Instead of the line:
System.out.println (generator.nextInt()%49);

Try using:

System.out.println (generator.nextInt(49) + 1);

The nextInt(int x) method of class Random will generate a random number between 0 and 48. Adding 1 will get you between 1 and 49 inclusive.

You may be getting duplicates because the Random class (when instanciated) is seeded with the current system time (System.currentTimeMillis()) and if your code runs fast enough, You could get some duplicate numbers.

Placing some time consuming code in the middle might slow it down enough to get a better random sample of numbers.
 
That makes a lot more sense for a beginner like me. Thanks for the tips!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top