在if条件JAVA中从sc.nextLine()获取输入的问题
System.out.print("Enter the key: ");
int n=sc.nextInt();
if(n==1)
{
System.out.println("Enter the task:");
String k=sc.nextLine();
System.out.println(k);
}
输入密钥:正在打印,给出 n=1 后,它只是打印 输入任务:,整个程序终止。但是,当我给 sc.next() 它工作,但我的输入有多个单词时,sc.nextLine() 是否有任何问题。
System.out.print("Enter the key: ");
int n=sc.nextInt();
if(n==1)
{
System.out.println("Enter the task:");
String k=sc.nextLine();
System.out.println(k);
}
Enter the key: is printing, after giving n=1, it just print
Enter the task: and the whole program is terminated. But when I give sc.next() it working but my input has more than one word, is there any problem in sc.nextLine().
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下,每当编写scanner.nextInt()时,该方法都不会返回换行符或不接受用户的任何输入。因此,如果您想要完美的输出,那么您需要在从用户获取字符串值之前放置scanner.next()。之后你可以使用scanner.nextLine(),它会正常工作。
Whenever write scanner.nextInt() in that case this method doesn't return new line character or don't accept any input from user. So if you want perfect output then you need to put scanner.next() before getting string value from user. After that you can use scanner.nextLine() and it will be work fine.
这是一个常见的概念问题。阅读这三个函数的java文档。同时你可以尝试下面的代码。它会起作用的。
This is a common conceptual problem. Read the java docs of these three functions. Meanwhile you can try the following code. It'll work.
答案和解决方法位于此处。
The answer and the workaround are here.