2015-06-27 70 views
2

我想使用element()方法打印这个名称队列的头部,但它不知道怎么做。
可以以某种方式请解释为什么它不?Java:使用元素()打印队列头

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

回答

2

队列中的第一个元素是一个空字符串。 这就是为什么strings.element()返回一个空字符串,并看到输出The name in front of the queue is:

为了消除空字符串添加:

int n= input.nextInt(); 
input.nextLine(); // this 

说明:主叫nextInt后,下一个nextLine将消耗包含所读取的整数线的端部,所以第一strings.add(input.nextLine());将添加一个空字符串到队列。

+0

谢谢!我知道了..其实,我已经把它从'strings.add(input.nextLine());'改为'strings.add(input.next());'现在它工作正常.. – Tia

+0

但是,我仍然在你说'nextLine'会消耗包含读取的整数的行的末尾......'时,你给出的解释似乎有些遗憾......你能再解释一遍吗? – Tia

+0

@Diksha假设你输入5然后回车。 'nextInt'将返回5.下一个'nextLine'将读取包含5的行的其余部分,该行仅包含新行字符,剥离新行字符并返回空字符串。只有下一行'nextLine'将从下面的行中读取。 – Eran