简体   繁体   中英

comparing an int with an array java

I am working on a project that has me scan for numbers 1-9 then storing them in an array, all the while checking for repeats. I can get everything except the part where I have to check for repeats. Is there an easy way to compare 1 number with an entire array?

ex. int[] array = new int[9];
        array[0] = 0;
        array[1] = 1;
        array[2] = 2;
        array[3] = 3;
        array[4] = 4;



then user inputs 3, how can I check the entire array for 3?

If you just want a way to see if the array contains the number 3 as stated in your question, you could just add a simple for loop.

 int[] array = new int[9];
    array[0] = 0;
    array[1] = 1;
    array[2] = 2;
    array[3] = 3;
    array[4] = 4;

    int num = 3;


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

        if(num==array[i]){
            System.out.println("found at index: " + i);
        }

You could easily adapt this to read in a value from the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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