I'm trying to get the secret code from 1 - 40, not to repeat any numbers. How am I able to compare each of them and not get any duplicates?
I have extensively looked through Java documentation and asked my lectures and I can't get a working answer. I understand the concept, what I'm meant to do, but just can't get the coding right.
Here is my code:
public static void main(String[] args) {
int[] secret = new int[5];
//int[] secret = {0,0,0,0,0};
int[][] num = new int[3][5];
int correctL1 = 0;
int correctL2 = 0;
int correctL3 = 0;
for (int i = 0; i<5; i++){ // to get secret numbers.
secret[i] = (int) ((Math.random() * (40 - 1)) + 1);
}
System.out.println(Arrays.toString(secret));
}
I have tried putting this into the loop to get another number but it's still giving me duplicates.
if(((secret[i] == secret[0]) || (secret[i] == secret[1]) ||
(secret[i] == secret[2]) || (secret[i] == secret[3]) ||
(secret[i] == secret[4])) || (secret[i] != 0)) {
secret[i] = ((int) ((Math.random() * (40 - 1)) + 1));
}
nullelements and duplicates, and Sets, which support uniqueness of elements. So the easieast approach is to collect the input data in anHashSet.