Results 1 to 4 of 4
  1. #1
    lilleza87 is offline Member
    Join Date
    Oct 2010
    Posts
    4
    Rep Power
    0

    Default Can I get random.util not to generate the same number twice

    Hi! I'm very new to Java and I'm trying to learn. I wanted to do a simple project where I use random to generate 4 random numbers between 1 and 35.
    These are my two methods:

    public void Lotto1(){
    Message1("Lotto1");
    Random randomGenerator = new Random();
    for (int i = 1; i <= 4; ++i){
    int randomInt = randomGenerator.nextInt(35);
    Message1(" " + randomInt);
    }

    public void Lotto2(){
    Message1(" \nLotto2 ");
    Random randomGenerator = new Random();
    for (int i = 1; i <= 4; ++i){
    int randomInt = randomGenerator.nextInt(35);
    Message1(" " + randomInt);
    }

    So my problem is this. I would really like to know if there is a way to stop Random from generating the same number twice in the same method. And also to stop it from generating the same number twice in both methods.
    What I mean is, if the number 8 is generated in the first method I'd like it to be generated once only in both the same method(lotto1) and the second metod.(lotto2) I would love some help.
    Thank you

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    One way is to use an ArrayList<Integer>, to fill it with 35 Integers, shuffle it via Collections.shuffle(myList), and then remove the 0th item from the list.

    Another way is to use a while loop, and keep selecting random numbers until a non-selected number has been chosen.

  3. #3
    lilleza87 is offline Member
    Join Date
    Oct 2010
    Posts
    4
    Rep Power
    0

    Default

    Thanks for your quick reply. Do you maybe have a code example I could look at? Like I said I'm really new to this :P I'll look into Arraylists and while loops.

  4. #4
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

Similar Threads

  1. Replies: 8
    Last Post: 04-19-2009, 05:50 PM
  2. Replies: 3
    Last Post: 04-16-2009, 01:42 AM
  3. Trying to Generate Random number
    By PeterFeng in forum New To Java
    Replies: 10
    Last Post: 01-14-2009, 08:37 AM
  4. Generate a random number
    By romina in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 05:23 AM
  5. How to generate random number in java
    By fernando in forum New To Java
    Replies: 1
    Last Post: 08-01-2007, 07:32 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •