Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a Method in Java that will return a Queue containing only the even numbers

ID: 3829211 • Letter: W

Question

Write a Method in Java that will return a Queue containing only the even numbers of a given queue. For example if the given queue is {2, 5, 8, 20, 27} then the returned queue must contain {2,8,20}.

Write a Method in Java that will return a Queue containing only the odd numbers of a given queue. For example if the given queue is {2, 5, 8, 20, 27} then the returned queue must contain {5,27}.

Once the execution returns to the caller method, the given queue should contain exactly the same elements in the same sequence as before making the call. Assume that a standard Queue class is available. You may NOT create any temporary container inside the method. That is, creation of arrays, vectors, lists, stacks, or any other temporary queue that is not returned is prohibited in this method. The header of the method is provided below.

}

}

Explanation / Answer

QueueTest.java

import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Queue;


public class QueueTest {

  
   public static void main(String[] args) {
      
       Queue<Integer> myQueue = new ArrayDeque<Integer>();
       myQueue.add(2);
       myQueue.add(5);
       myQueue.add(8);
       myQueue.add(20);
       myQueue.add(27);
       System.out.println(returnEvenNumbers(myQueue));
       System.out.println(returnOddNumbers(myQueue));
   }
   public static Queue returnEvenNumbers(Queue q){
       Queue<Integer> evenQueue = new ArrayDeque<Integer>();
       Iterator<Integer> iterator = q.iterator();
       while(iterator.hasNext()){
       int n = iterator.next();
       if(n % 2 == 0){
           evenQueue.add(n);
       }
       }
       return evenQueue;
   }
     
   public static Queue returnOddNumbers(Queue q){
       Queue<Integer> oddQueue = new ArrayDeque<Integer>();
           Iterator<Integer> iterator = q.iterator();
           while(iterator.hasNext()){
           int n = iterator.next();
           if(n % 2 != 0){
               oddQueue.add(n);
           }
           }
           return oddQueue;
   }
}

Output:

[2, 8, 20]
[5, 27]

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote