for (int i = 0; i < size; i++) { a[i] = (int)(Math.random()*10); for (int j = 0; j < i; j++) { if (a[i] == a[j]) { a[j] = (int)(Math.random()*10); //What's this! Another random number! } } }您确实找到重复的值。但是,您将其替换为另一个可能重复的随机数。相反,请尝试以下操作:
for (int i = 0; i < size; i++) { a[i] = (int)(Math.random()*10);//note, this generates numbers from [0,9] for (int j = 0; j < i; j++) { if (a[i] == a[j]) { i--; //if a[i] is a duplicate of a[j], then run the outer loop on i again break; } } }但是,这种方法效率低下。我建议列出数字,然后将其随机化:
ArrayList<Integer> a = new ArrayList<>(11);for (int i = 0; i <= 10; i++){ //to generate from 0-10 inclusive. //For 0-9 inclusive, remove the = on the <= a.add(i);}Collections.shuffle(a);a = a.sublist(0,4);//turn into array或者您可以这样做:
ArrayList<Integer> list = new ArrayList<>(11);for (int i = 0; i <= 10; i++){ list.add(i);}int[] a = new int[size];for (int count = 0; count < size; count++){ a[count] = list.remove((int)(Math.random() * list.size()));}


