I have to write a program that creates a queue of Strings. It asks the user to input a number n for which he will have to enter n number of names in the queue. Then until the queue is empty, the program
The program should use only the add(), remove(), isEmpty() and element() methods. Here is what I have come up with so far:
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));
}
}
}
}
The problem is that it is printing false for the names being deleted because remove() is a boolean method. How can I fix this?
Both poll
and remove
returns the deleted object but poll does not throw exceptions if that the problem, no one of them return boolean.
for (int i = 0; i < del; i++) {
System.out.println("Name removed:" + strings.poll());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.