简体   繁体   English

检查数组是否包含某些整数

[英]Checking if an array contains certain integers

I am making an Array that is 10 integers long, so that each place 0-9 contains a different integer 0-9. 我正在制作一个长度为10个整数的数组,因此每个位置0-9都包含一个不同的整数0-9。

I am having trouble figuring out how to check if the array already contains a certain number, and if so, regenerating a new one. 我在弄清楚如何检查数组是否已经包含某个数字时遇到麻烦,如果是,则重新生成一个新的数字。

So far I have: 到目前为止,我有:

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

    perm[i] = num;   
}
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 总体而言 ,对于此任务,您最好按顺序用值初始化数组,然后使用随机排列索引对其进行混洗

here is a complete answer 这是一个完整的答案

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);

Adding both string and integer to check is exist or not. 添加字符串和整数以检查是否存在。

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();
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM