让我猜一下 – 你没有显示使用上面尝试获取lastName的扫描器的代码.在那次尝试中,你没有处理行尾令牌,所以它是悬空的,只是被你试图获取lastName的nextLine()调用吞噬.
例如,如果你有这个:
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = keyboard.nextInt(); // dangling EOL token here
System.out.print("Last name: ");
lastName = keyboard.nextLine();
你会遇到问题.
一种解决方案,每当你离开EOL令牌悬空时,通过调用keyboard.nextLine()来吞下它.
例如.,
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = keyboard.nextInt();
keyboard.nextLine(); // **** add this to swallow EOL token
System.out.print("Last name: ");
lastName = keyboard.nextLine();