这样说:
int age = input.nextInt();input.nextLine();System.out.println("Great! We're almost done. What are three interests you have?");String interests = input.nextLine();其余代码可能与您上面的代码相同。
编辑:
它必须是这样的(我的意思是,不将行存储在您的任何变量中),因为
nextInt()函数不会读取整行,而只是读取下一个整数。因此,当
nextInt()函数读取时
int,的“光标”
Scanner将位于之后的位置
int。
例如,如果您在尝试读取时输入多个单词(用空格隔开)
int,则在您的兴趣变量中,您将
nextInt()读取之前无法读取的其余行。因此,如果您有:
System.out.println("Okay, " + name + ", you are a " + gender + ". Now, tell me, what is your age?");//Here you enter --> 18 This is a proveint age = input.nextInt();System.out.println("Great! We're almost done. What are three interests you have?");//Here you won't be able to put anythingString interests = input.nextLine();现在您将存储:
age = 18;interests = "This is a prove";
但是,如果您将代码如下所示:
System.out.println("Okay, " + name + ", you are a " + gender + ". Now, tell me, what is your age?");//Here you enter --> 18 This is a proveint age = input.nextInt();input.nextLine();//Now the Scanner go to a new line (because of the nextLine) but without storing the valueSystem.out.println("Great! We're almost done. What are three interests you have?");//Now you are in a new line and you are going to be able to write. For example --> I am reading this.String interests = input.nextLine();您现在要拥有的值是:
age = 18;interests = "I am reading this.";
因此,总而言之,如果您有一个
nextInt()并且试图读取一个
int,则可以读取它,但是光标将停留在该行的最后,您将无法读取下一行。为此,您必须阅读完整的行而不将其存储在中
input.nextLine();。
希望对您有帮助!



