I'm quite new to Java so please bear with me. I wrote this program:
public static void main(String args[])
{
int[] list = {1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 10};
isUnique(list);
System.out.println(isUnique(list));
}
private static boolean isUnique(int[] array)
{
int count = 0;
for (int n : array)
{
for (int i = 0; i < array.length; i++)
{
if (n == array[i])
{
count++;
}
if (count > 1)
{
return false;
}
else
{
return true;
}
}
}
return false;
}
}
It's supposed to check the array and see, if there are any more than 1 of each number. However it doesn't seem to work. It returns true even if there are two 1's. Any ideas? I suspect the for loop isn't working, but I'm not quite sure why.
Thanks in advance!
It returns true no matter what because you have that else block. Because count starts up zero and it increases a maximum of one time per loop, that else block will always run (if the array length is not 0). You can think of this as two cases:
Case 1. n == array[i] --> count will equal 1 --> count>1 is not true --> else block runs and returns true.
Case 2. n is not array[i] --> count equals 0 --> count>1 is not true --> else block runs and returns true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With