简体   繁体   中英

Java: Printing out the head of a queue using element()

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());
    }
}

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM