0

我正在制作一个长度为 10 个整数的数组,因此每个位置 0-9 包含一个不同的整数 0-9。

我无法弄清楚如何检查数组是否已经包含某个数字,如果是,则重新生成一个新数字。

到目前为止,我有:

for (int i = 0; i < perm.length; i++)
{
    int num = (int) (Math.random() * 9); 
    int []

    perm[i] = num;   
}
4

3 回答 3

3
Arrays.asList(perm).contains(num) 

from How can I test if an array contains a certain value?

for (int i = 0; i < perm.length; i++)

this is not enough to loop like this, if collision happens some slots would have been not initalized.

Overall, for this task you better initialize array with values in order and then shuffle it by using random permutation indexes

于 2012-12-09T16:12:28.180 回答
0

这是一个完整的答案

int[] array = {3,9, 6, 5, 5, 5, 9, 10, 6, 9,9};

    SortedSet<Integer> s = new TreeSet();
    int numberToCheck=61;
    for (int i = 0; i < array.length; i++) {
        s.add(array[i]);
    }

    System.out.println("Number contains:"+!(s.add(numberToCheck)));


    System.out.println("Sorted list:");
    System.out.print(s);
于 2015-05-20T19:15:16.370 回答
0

添加字符串和整数来检查是否存在。

public class existOrNotInArray {

public static void elementExistOrNot() {
    // To Check Character exist or not
    String array[] = { "AB", "CD", "EF" };

    ArrayList arrayList = new ArrayList<>();

    String stringToCheck = "AB";

    for (int i = 0; i < array.length; i++) {
        arrayList.add(array[i]);
    }

    System.out.println("Character exist : " + arrayList.contains(stringToCheck));

    // To Check number exit or not
    int arrayNum[] = { 1, 2, 3, 4 }; // integer array

    int numberToCheck = 5;

    for (int i = 0; i < arrayNum.length; i++) {
        arrayList.add(arrayNum[i]);
    }
    System.out.println("Number exist :" + arrayList.contains(numberToCheck));
}

public static void main(String[] args) {
    elementExistOrNot();
}
}
于 2018-08-03T16:26:36.393 回答