0

I have been working on a bingo game for class and I have a problem with repeating numbers. I understand how to create non-repeating random numbers with arrays but not for a normal integer or string. I will show an example of what I am going for.

String var = null;
        int ranVar;
        final Random ran = new Random();
        ranVar = ran.nextInt(74) + 1;
        boolean match;
// Attempted the code for non-repeating numbers here:
        for (int i = 0; i < 1; i++) {
            if (ranVar <= 15) {
                match = false;
                return var = "B" + ranVar;
                for (int x = 0; x <= i; x++) {
                    if (ranVar == x) {
                        match = true;
                    }
                }
                if (match == true) {
                    i = i - 1;
                } else ranVar = i;
            }else if (ranVar <= 30) {
                return var = "I" + ranVar;
            } else if (ranVar <= 45) {
                return var = "N" + ranVar;
            } else if (ranVar <= 60) {
                return var = "G" + ranVar;
            } else if (ranVar <= 75) {
                return var = "O" + ranVar;
            }

        }

As you can see I have attempted to do this with the B value, but was unsuccessful. Any help is appreciated.

Peter O.
  • 32,158
  • 14
  • 82
  • 96
  • Does this answer your question? [Generating Unique Random Numbers in Java](https://stackoverflow.com/questions/8115722/generating-unique-random-numbers-in-java) – Curiosa Globunznik Dec 03 '19 at 01:12
  • Reading your code it's a bit unclear what you are trying to do. `var` is a local variable but you seem to be assigning it a value before returning from the method. Why are you adding the "B" (or one of the other letters) before the value? – sprinter Dec 03 '19 at 02:57
  • Does this answer your question? [Random shuffling of an array](https://stackoverflow.com/questions/1519736/random-shuffling-of-an-array) – Peter O. Dec 03 '19 at 06:26

1 Answers1

0

If you wish to check if a value has already been used each time you call the method then you will need to store the previous values in a collection. A nice simple way to do this is to use a set and test the return value of add.

For example, if you are generating random strings:

private final Set<String> values = new HashSet<>();

public String getValue() {
    String value;
    do {
        value = generateValue();
    } while (!values.add(values));
    return value;
}
sprinter
  • 27,148
  • 6
  • 47
  • 78