HY2000
HY2000

Reputation: 181

Compare a list of integers with an integer to find the largest

I need to write a code to returns true if the first argument contains a number greater than the second argument; returns false otherwise. Given that a list of integers(first argument) is compared to an integer(second argument). I must use Iterator to implement this function.

This is the code I have so far:

public class ListHasGreater {    
    public static boolean hasGreater(List<Integer> numbers, int number) {
        // write your code here
        Iterator<Integer> selectedNum = numbers.iterator();
        
        if (selectedNum.hasNext()){
            int result = selectedNum.next();
            while (result > number){
                return true;
            }
            return false;
        }  
    }
}

And I got this error error: class, interface, or enum expected

I'm not sure if my code is logically correct and don't know how to solve this error.

Upvotes: 0

Views: 340

Answers (2)

Abhishek Khedekar
Abhishek Khedekar

Reputation: 76

You are returning from a conditional, you should also add a return statement at the end of loop. Instead of while (result > number){return true;} it should be if(result > number) return true

Upvotes: 2

Richard Stokes
Richard Stokes

Reputation: 543

The explicit use of iterators is quite an old way of programing, instead you can use a foreach loop and let Java convert this into iterators at compilation.

public static boolean hasGreater(List<Integer> numbers, int number) {

    for (int numInList : numbers) {
        if (numInList > number) {
            return true;
        }
    }
    return false;
}

Upvotes: 2

Related Questions