为什么扫描仪输入不起作用?

所以我是一个新的Java程序员,我试图弄清楚为什么一段代码不起作用。 我遇到的问题是:“String interests = input.nextLine();”,它跳过用户的输入并跳转到下一个System.out,所以它只是在控制台中显示“你的个人资料……”在允许用户输入任何数据之前。 对不起,如果这是一个愚蠢的问题,我很新!

System.out.println("Hello, " + name + "! What is your gender?"); String gender = input.nextLine(); System.out.println("Okay, " + name + ", you are a " + gender + ". Now, tell me, what is your age?"); int age = input.nextInt(); System.out.println("Great! We're almost done. What are three interests you have?"); String interests = input.nextLine(); System.out.println("...Your profile..."); System.out.println("Name: " + name); System.out.println("Gender: " + gender); 

这样说:

 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()函数读取intScanner的“光标”将位于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 prove int 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 anything String 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 prove int age = input.nextInt(); input.nextLine(); //Now the Scanner go to a new line (because of the nextLine) but without storing the value System.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();

我希望它对你有所帮助!

尝试使用System.console()。readLine();

请说明您如何申报Scanner

仅供参考,以这种方式完成。

 Scanner sc = new Scanner(System.in); ... System.out.println("Hello, " + name + "! What is your gender?"); String gender = input.nextLine(); ... 

我假设当您声明扫描程序时,您没有执行Scanner input = new Scanner(System.in)您需要在使用扫描程序时将System.in放在括号中。 所以它是String gender = input.nextLine();

您的:

 String interests = input.nextLine(); 

正在被跳过,因为没有一行的结尾,请查看此处了解更多信息,您可以尝试使用next()重新设置所有你的nextLine()