How would i prevent duplicating numbers from random numbers. I need to generate 5 numbers between 1 and 9 that are each different. I would often get same numbers like 23334, how can i prevent that? Any help would be great!
int num2 = (int) Math.round((Math.random()*9) +1);
int num1 = (int) Math.round((Math.random()*9) +1);
int num5 = (int) Math.round((Math.random()*9) +1);
int num3 = (int) Math.round((Math.random()*9) +1);
int num4 = (int) Math.round((Math.random()*9) +1);
If the number of possible random values is small, you want to use shuffle.
If the number of possible random values is large, you want to test adding them to a Set (or the original list if small enough)
Note: you need to shuffle the set as it doesn't preserve order. e.g. the numbers 1,2,3 will always come out in that order with HashSet, not 3,2,1.
How about this?