# Same values in an array

• 02-24-2009, 08:01 PM
hawaiifiver
Same values in an array
Hello to all,

I am wondering how to compare values in an array to see if any two values are the same.

can i use nested for loops with this?

Thanks.
• 02-24-2009, 08:13 PM
Fubarable
Quote:

Originally Posted by hawaiifiver
can i use nested for loops with this?

That's the beauty of programming -- you have the ability and freedom to create something, and when doing this, you can try almost anything out. If it doesn't work, no harm, no foul.

So my advice: sure give it a try, you've nothing to lose.

Good luck.
• 02-24-2009, 08:54 PM
hawaiifiver
Hi all. I worked the following out. It works if there are two values. Like if i enter 2,3,3,4,5 or 5,6,7,8,6. But it wont work with 4,5,4,6,4. Any ideas?

Code:

```class Array {         public static void main (String [] args)         {         int [] array = new int[5];         int count = 0;         System.out.println("Please enter five numbers:");         for (int i = 0; i < array.length; i ++)         { array[i] = Console.readInt(); }         System.out.println();         System.out.println();         for (int i = 0; i < array.length; i ++)         {         for (int j = 1; j < array.length; j++)         {         if (array[i] == array[j] && j != i)         count++;         }         }         System.out.println();         System.out.println(count);         }// main }// class```
• 02-24-2009, 09:33 PM
angryboy
its better to say:
for (int j = i+1; j < array.length; j++)

edit:
and i would zero out the matched numbers. (or make it -1 or whatever)
if (array[i] == array[j] && array[j] != 0)
count++;
array[j] = 0;
}