Rachdi O
Rachdi O

Reputation: 1

How to generate random unique numbers on java

I'm new to Java and im trying to randomize non-repeating numbers for a game. My code generates unique random numbers from 1 to 75 only if i do not add a break statement, (which i have to do to only get one number at the time). What do I do? edit -(i was wondering if the reason it kept resetting is because i called on the method multiple times? im not too sure how to fix that)

public static void genNumber() {
    Random random = new Random();

   int num;
    String u; 
    String letter = "";
    HashSet<Integer> used = new HashSet<>(75);
        for (int i = 1; i <= 75; i++){
            ball.add(i);
        }

   while(used.size() > 0) {

    num = 1 + random.nextInt(75);

        if (used.contains(num)){
            used.remove(new Integer(num));


        u = Integer.toString(num); 
        System.out.print(u + "\n");
break; 

        }
        if (!used.contains(num)){
            continue;
        }
       }

The numbers are unique and random but i only want one number at the time (without repeating) not all 75 at once.

Upvotes: 0

Views: 493

Answers (2)

jspcal
jspcal

Reputation: 51924

Perhaps shuffle the list each time you want a new random sequence, like a deck of cards. Each element is guaranteed to be unique.

List<Integer> balls = new ArrayList<>();

for (int i = 1; i <= 75; ++i) {
    balls.add(i);
}

for (;;) {
    // Shuffle the list every 75 draws:

    Collections.shuffle(balls);
    System.out.println(Arrays.toString(balls.toArray()));

    // Consume the sequence

    for (Integer ball : balls) {
        take(ball);
    }
}

Upvotes: 1

G Schunk
G Schunk

Reputation: 23

I would make a 75 element array of boolean values and set all the values to true. Make a method that generates one random number and update your boolean array at that value to false. Each time you generate a number check your array to see if that value is set to true. Then you can keep generating numbers one at a time and not have to worry about getting repeats. You can have a while loop that asks the user to input yes or no and if they answer no it won't call your method and set your while loop condition to false. and if they answer yes it does call the method and keeps looping.

Upvotes: 0

Related Questions