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;
}
}
}
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 rawIteratorif you want auto-unboxing to work.It would also be more concise and readable by using a foreach loop:
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.