Reputation: 1230
I want to print the head of this queue of names using the element() method but it somehow doesn't.
Can somehow please explain me why it doesn't?
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.nextLine());
}
for(String object: strings){
System.out.println(object);
}
System.out.println("The name in front of the queue is: " + strings.element());
}
}
Upvotes: 2
Views: 1761
Reputation: 393771
The first element in your Queue is an empty String.
This is why strings.element()
returns an empty String and you see the output The name in front of the queue is:
.
To eliminate the empty String add :
int n= input.nextInt();
input.nextLine(); // this
Explanation: After calling nextInt
, the next nextLine
will consume the end of the line that contained the integer that was read, so the first strings.add(input.nextLine());
will add an empty String to the Queue.
Upvotes: 2