ferit enişer
ferit enişer

Reputation: 41

What is the issue with "iterator.next()%2 "?

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

Answers (3)

satvinder singh
satvinder singh

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

Bharat Sinha
Bharat Sinha

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

JB Nizet
JB Nizet

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

Related Questions