1

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?
  • Check out: http://stackoverflow.com/questions/1128723/how-can-i-test-if-an-array-contains-a-certain-value – roger Feb 17 '17 at 02:30
  • 1
    Possible duplicate of [How can I test if an array contains a certain value?](http://stackoverflow.com/questions/1128723/how-can-i-test-if-an-array-contains-a-certain-value) – BusyProgrammer Feb 17 '17 at 02:34
  • @ABusyProgrammer Not really a duplicate, because that question is about a `String` array, and most of the answers given won't work for an array of primitives such as `int`. – Dawood ibn Kareem Feb 17 '17 at 02:35
  • Yes, but your question is also indirectly answered there too. – BusyProgrammer Feb 17 '17 at 02:37

1 Answers1

0

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.

RSon1234
  • 394
  • 4
  • 14