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());
}
}
谢谢!我知道了..其实,我已经把它从'strings.add(input.nextLine());'改为'strings.add(input.next());'现在它工作正常.. – Tia
但是,我仍然在你说'nextLine'会消耗包含读取的整数的行的末尾......'时,你给出的解释似乎有些遗憾......你能再解释一遍吗? – Tia
@Diksha假设你输入5然后回车。 'nextInt'将返回5.下一个'nextLine'将读取包含5的行的其余部分,该行仅包含新行字符,剥离新行字符并返回空字符串。只有下一行'nextLine'将从下面的行中读取。 – Eran