Java中使用hasNextLine,在NextInt之后不会读取NextLine
我正在尝试让它工作
System.out.println("Please enter what SOCKET NUMBER you" +
"wish to connect to");
int sockname = Integer.parseInt(inFromUser.nextLine());
System.out.println("Please enter what HOSTNAME you" +
"wish to connect to");
String hostname = inFromUser.nextLine();
问题是我无法让主机名等于用户输入的任何内容。我认为这与 hasNext 或它的变体有关,但我不确定。有什么想法吗?
I am trying to get this to work
System.out.println("Please enter what SOCKET NUMBER you" +
"wish to connect to");
int sockname = Integer.parseInt(inFromUser.nextLine());
System.out.println("Please enter what HOSTNAME you" +
"wish to connect to");
String hostname = inFromUser.nextLine();
The problem is that I can't get hostname to equal whatever the user input. I thought it had to do with hasNext or a variant of that, but I'm not sure. Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
nextLine() 之后的输入缓冲区中可能有“\n”,因此 next 调用只会读取它并返回。读取int后需要清除缓冲区
There might be "\n" in the input buffer after nextLine(), so next call just reads it and returns. You need to clear the buffer after reading int
java.io.BufferedReader 有一个 readLine() 方法。用那个。如果您使用 Scanner.nextLine(),那么您应该知道,如果您的位置正好在换行符之前,您将得到一个空字符串。然而,下一个 nextLine 确实会返回一整行文本(与 readLine 相同)。
java.io.BufferedReader has a readLine() method. Use that. If you're using Scanner.nextLine(), then you should know that if your position is just before a newline, you'll get an empty string. However, the next nextLine would indeed return a full line of text (the same as readLine would).