我在返回用户输入字符串时遇到困难.如果我有一个代码:
System.out.println("please enter a digit: ");
number1 = in.nextInt();
System.out.println("enter another digit: ");
number2 = in.nextInt();
System.out.println("enter a string: ");
string = in.nextLine();
//calculations
System.out.println(number1);
System.out.println(number2);
System.out.println(string);
Run Code Online (Sandbox Code Playgroud)
它打印出数字但不打印字符串.我觉得这个解决方案非常简单,但我现在正在做脑屁.任何帮助,将不胜感激!
你需要in.nextLine()在调用in.nextLine()字符串之前调用额外的函数.它是消耗额外的新行字符.
至于解释,我们以此输入为例:
23[Enter]
43[Enter]
Somestring[Enter]
Run Code Online (Sandbox Code Playgroud)
(23和43可以是任意数字,重要的部分是新行)
您需要调用in.nextLine()以使用上一行中的新行in.nextInt(),尤其是43上面示例中的新行字符.
nextInt()将消耗尽可能多的数字,并在下一个字符为非数字时停止,因此新行就在那里.nextLine()会读到所有内容,直到遇到新行.这就是为什么你之后需要一个额外nextLine()的删除新行43,以便你可以继续阅读Somestring下一行.
例如,如果您的输入是这样的:
23 43 Somestring[Enter]
Run Code Online (Sandbox Code Playgroud)
你不按Enter键只是继续键入,然后你当前的代码将显示字符串(这将是 Somestring,注意空格),因为之后没有新行阻塞43.