Java正在跳过一条线(扫描仪中的字符串??)

我正在学习Java,我不是很了解它,我不知道为什么,但Java似乎跳过了一条线。 我认为我的所有页面中的代码都不是真的很糟糕,所以我会把第一页和我使用它时得到的结果放在一起。 谢谢!

import java.util.Scanner; public class First { public static void main(String args[]){ Scanner scanz = new Scanner(System.in); System.out.println("Hello, please tell me your birthday!"); System.out.print("Day: "); int dayz = scanz.nextInt(); System.out.print("Month: "); int monthz = scanz.nextInt(); System.out.print("Year: "); int yearz = scanz.nextInt(); System.out.println("Now, tell me your name!"); System.out.print("Name: "); String namez = scanz.nextLine(); Time timeObject = new Time(dayz,monthz,yearz); Second secondObject = new Second(namez,timeObject); System.out.println("\n\n\n\n\n" + secondObject); } } 

它会跳过这条线

  String namez = scanz.nextLine(); 

控制台输出:(原谅生日位,这是其他东西)

 Hello, please tell me your birthday! Day: 34 Month: 234 Year: 43 Now, tell me your name! Name: My name is and my birthday is 00/00/43 

它没有给你机会给出一个名字,它只是直接跳过并将名称取为null。 如果有人能,请告诉我原因! 我想学习Java,这种小烦恼正在阻碍着我。

谢谢!

问题是nextLine获取行上的任何字符,并且\ n(换行符)从上面的扫描仪输入中遗留下来。

因此,不是让你输入新内容,而是将\ n作为输入并继续。

要修复,只需将两个扫描仪背对背,如下所示:

 System.out.print("Name: "); scanz.nextLine(); String namez = scanz.nextLine(); 

只是使用:

 String namez = scanz.next(); 

也会工作,但会将名称限制为一个单词。 (仅限名字)

我相信nextLine是正确的。 但问题是nextInt不会创建换行符号,而是读取该行的其余部分(为空)。 我相信如果在此之后添加另一个nextLine语句,代码将起作用。 另一方面,接下来只识别第一个单词,这可能不是正确的解决方案。