109k views
4 votes
Write a function findEvenQueue that returns the first even number in the Queue. The function looks at the value at the front of the queue and checks if it’s even. If the value is even, then it returns that number. If the value is not even, then it removes that item from the queue and the process is repeated checking the front of the queue again. The function should return -1 if there are no even numbers. HINT: The program should make use of the peek method and the poll method of the queue.

User Hester
by
4.5k points

1 Answer

2 votes

Answer:

Check the explanation

Step-by-step explanation:

CODE:

static int findEvenQueue(Queue<Integer> numbers)

{

//loop runs till the queue has atleast one element

while(numbers.size() > 0)

{

//Checking the head of the queue whether it is even

int temp = numbers.peek();

if(temp % 2 == 0)

{

//if the head is even then return it

return temp;

}

else

{

//else remove the number at head

int removed = numbers.poll();

}

}

//if no even number present in the Queue then return -1

return -1;

}

User Martin Kool
by
4.6k points