我是一名初学者java程序员,我试图考虑一下能否检查数组中是否存在多个相同数字的函数,如果它确实存在一个新的随机数数组 这就是我得到的:
for (int i = 1; i < number.length; i++) {
if (number[i] == number[i - 1])
putTextOnButtons();
}
private void putTextOnButtons() {
for (int i = 0; i < 4; i++) {
int num = rand.nextInt(50) + 1;
number[i] = num;
}
但我不知道在使用putTextOnButtons()函数后如何检查 提前致谢! 没关系,我得到了它,我使用了这样的递归:
private void putTextOnButtons() {
for (int i = 0; i < 4; i++) {
int num = rand.nextInt(15) + 1;
number[i] = num;
buttons[i].setText(num + "");
sortArray(number);
for (int j = 1; j < number.length; j++) {
if (number[i] == number[i - 1])
putTextOnButtons();
}
sortArray(number);
}
}
答案 0 :(得分:0)
您可以手动或使用Set进行检查。
手动检查:
int[] numbers = new int[]{1, 2, 3, 4, 5, 5, 6};
boolean found = false;
for (int i=0; i<numbers.length; i++) {
for (int j=i+1; j<numbers.length; j++) {
if (numbers[i]==numbers[j]) {
found = true;
break;
}
}
if (found) {
break;
}
}
//System.out.println(found);
if (found) {
// do what you want
}
使用设置检查:
Integer[] numbers = new Integer[]{1, 2, 3, 4, 5, 5, 6};
HashSet<Integer> numberSet = new HashSet<Integer>(Arrays.asList(numbers));
boolean found = (numbers.length>numberSet.size());
//System.out.println(found);
if (found) {
// do what you want
}
答案 1 :(得分:0)
试一试,告诉我它是否有效!和平。
duplicates=false;
for (j=0;j<number.length;j++)
for (k=j+1;k<number.length;k++)
if (k!=j && number[k] == number[j])
{
duplicates=true;
putTextOnButtons();
}
答案 2 :(得分:0)
这样做
for (i=0;i<number.length;i++)
{
for (j=i+1;j<number.length;j++)
{
if (j!=i && number[j] == number[i])
{
// Get random value
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
// Insert the random number if duplicate is found
number[j] = randomNum;
}
}
}