Java: 从队列中移除指定数量的元素

Java: removing a specified number of elements from a queue

我必须编写一个程序来创建字符串队列。它要求用户输入一个数字 n,为此他必须在队列中输入 n 个名字。然后直到队列为空,程序

  1. 在队列顶部显示名称
  2. 询问用户一些要删除的名字。
  3. 删除指定数量的名称
  4. 显示已删除的姓名

该程序应仅使用 add()、remove()、isEmpty() 和 element() 方法。 这是我到目前为止的想法:

package lesson1;
import java.util.*;


public class MyClass1{

public static void main(String[] args) {

Queue <String> strings= new LinkedList<String>();


Scanner input= new Scanner(System.in);

System.out.println("Please enter the number of names, n.");
int n= input.nextInt();

System.out.println("Please enter " +n+ " names");

for(int i=0;i<n; i++){

    strings.add(input.next());

}

System.out.println("\nDisplaying the names:\n");
for(String object: strings){

    System.out.println(object);
}

      while(!strings.isEmpty()){
        System.out.println("The name in front of the queue is: " + strings.element());


        System.out.println("Please enter the number of names to be deleted:");
        int del= input.nextInt();

        for(int i=0; i<del; i++){

        System.out.println("Name removed:"+strings.remove(i));

       }
      }

  }

}

问题是它正在为要删除的名称打印 false,因为 remove() 是布尔方法。我该如何解决这个问题?

pollremove return 都是已删除的对象,但是 poll 不会抛出异常如果那是问题,没有一个 return 布尔值。

for (int i = 0; i < del; i++) {
    System.out.println("Name removed:" + strings.poll());
}