Java Scanner 为什么我的代码中的 nextLine() 被跳过?
Scanner kb = new Scanner(System.in);
System.out.println("Inserting L");
int L = kb.nextInt();
System.out.println("Inserting N");
int N = kb.nextInt();
System.out.println("Inserting x");
String x = kb.nextLine();
System.out.println(x);
System.out.println("You inputed L,N,x");
为什么这段代码中没有提示nextLine()
?
Scanner kb = new Scanner(System.in);
System.out.println("Inserting L");
int L = kb.nextInt();
System.out.println("Inserting N");
int N = kb.nextInt();
System.out.println("Inserting x");
String x = kb.nextLine();
System.out.println(x);
System.out.println("You inputed L,N,x");
Why is there no prompt for nextLine()
in this code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用:
代替
kb.nextLine()
。这是因为
nextInt()
仅读取数字,而不是行尾或数字后面的任何内容。当您调用nextLine()
时,它会读取同一行的其余部分,并且不会等待输入。理想情况下,您应该在
nextInt()
代码后面调用kb.nextLine()
来忽略该行的其余部分。Use:
instead of
kb.nextLine()
.This is because
nextInt()
reads just the number, not the end of line or anything after the number. When you callnextLine()
it reads the remainder of the same line and does not wait for input.Ideally you should call
kb.nextLine()
the line after your code fornextInt()
to ignore the rest of the line.试试这个...
try this one...