Question

I have this assignment:

Print 5 random integer between 1-52 with no duplicate using if/else.

Here's my code so far. It prints some numbers, but it sometimes prints duplicates.

import java.util.Random;

public class RandomCards {

    public static void main(String[] args) {

        Random randomCards = new Random();
        int card;

        for (int x = 1; x <= 5; x++) {
            card = randomCards.nextInt(52) + 1;
        }
        if (card != randomCards) // if the value of card is not equal, proceed
        {
            System.out.print(card + " ");
        } else {
            return card; // if the value are the same get random integers again
        }
    }
}
Was it helpful?

Solution 2

You can use this

Random randomCards = new Random();
        int[] card={0,0,0,0,0};
        while(card[card.length-1] == 0) {
            int temp=randomCards.nextInt(52);
            for(int j=0;j< card.length ; j++){
             if(card[j] == 0){
                 card[j] = temp;
                 break;
             }
            }
        }
        for(int j=0;j< card.length ; j++){
         System.out.println(card[j]);
        }

OTHER TIPS

public static void main(String args[]) {
    Random randomNumber = new Random();
    // Set stores only Unique values
    Set<Integer> cards = new HashSet<Integer>();

    // Iterate over to generate random numbers
    while (cards.size() < 5) {
        int r = randomNumber.nextInt(52) + 1;
        cards.add(r);
    }
    for(Integer card : cards) {
        System.out.println(card);
    }
}

It's not clear what you're asking, but I note from your code that you don't have any duplicate detection. You need to save each value that you generate and check for duplicates when you create a new one. I suggest creating a Set<Integer> to hold your generated values, calling add() for each new card, and checking contains() to see whether a new value has already been selected. You'd want to change your loop condition to something like cards.size() < 5 as well.

Finally, note that your use of return card is incorrect and will result in a compile-time error. return is used to end a method and send a value back to where it was called from; the main method (which is always void) has no return value, and ending the method wouldn't make sense there anyway. It looks like some code may have been copied and pasted from a version where drawCard() was its own method. Instead, just keep looping until you find 5 unique cards (such as by using the size() method I mentioned earlier).

Maybe this?

Random rand = new Random();

// ArrayList to store non-duplicate cards.
ArrayList<Integer> cards = new ArrayList<Integer>();

// Iterate over to generate random numbers
while (cards.size() < 5)
{
    int r = rand.nextInt(52) + 1;

    if (!cards.contains(r))
        cards.add(r);        // Only add if there is no such number in list
}

Hope this helps.

Hope this would be of any help.

It comprises of separate methods for computation, setting the lower and upper bound and printing the list when it has 5integers in it. Using TreeSet solves your problem of duplicates. Here it goes,

package com.project.stackoverflow;

import java.util.Random;
import java.util.Scanner;
import java.util.TreeSet;

public class RandomGenerator {

    public TreeSet<Integer> compute() {
        TreeSet<Integer> generatedList = new TreeSet<Integer>();
        Scanner s = new Scanner(System.in);
        System.out.println("Enter the lower bound for checking random numbers:");
        long lowBound = s.nextLong();
        System.out.println("Enter the upper bound for checking random numbers:");
        long topBound = s.nextLong(); 
        Random randomNumbers = new Random();
        for (int i = 0; i < topBound; i++) {
            if (generatedList.size()==5) {
                break;
            }
            else {
            generatorFunc(lowBound, topBound,randomNumbers,generatedList);
            }
        }
        return generatedList;
    }

    public void generatorFunc(long lowBound,long topBound,Random randomNumbers, TreeSet <Integer> generatedList) {
        long limit = topBound - lowBound;
        long part = (long)(limit * randomNumbers.nextDouble());
        int randomNum = (int) (part + lowBound);
        generatedList.add(randomNum);
    }

    public void printList() {
        TreeSet<Integer> testListVals = compute();
        System.out.println("New" + testListVals);
    }

    public static void main(String[] args) {
        RandomGenerator obj = new RandomGenerator();
        obj.printList();
    }
}

If your problem is just about the duplicates, then you can store each random number generated in an array, and for every successive call to nextint(), check if it already exists in the array of stored values, and till it does, call nextint() again for that iteration itself, else store it in the array and go to next iteration.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top