Reputation: 41
What is problem with my code? I am trying to find whether the set contains any odd number
public static boolean hasOdd (Set<Integer> set) {
Iterator iterator;
iterator = set.iterator();
while (iterator.hasNext()) {
if(iterator.next()%2 != 0) {
return true;
} else {
return false;
}
}
}
Upvotes: 2
Views: 422
Reputation: 1152
or you can try like this
Iterator<Integer> iterator = set.iterator();
and don't use else in loop, and false statement should be the last statement of method
Upvotes: 0
Reputation: 14373
Your method is just checking for the first element of the set and telling whether that is odd or not. However you should make sure to break from loop only when you find first Odd Number.
Upvotes: 1
Reputation: 692081
The problem is that it only checks the first element of the iterator. It should not return if the current element is even, but go to the next element. Another problem is that you should use Iterator<Integer>
, and not just the raw Iterator
if you want auto-unboxing to work.
It would also be more concise and readable by using a foreach loop:
for (Integer i : set) {
...
}
This looks like homework, or at least something you could figure out yourself, so I won't give you the solution, but only the above hints.
Upvotes: 7