本文介绍了Java - Scanner - 跳过我上次的nextLine()请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我早先实例化扫描仪扫描
,但它跳过我的第二个 scan.nextLine()
在 scan.nextInt()
之后。我不明白为什么会跳过它?
So I instantiate the Scanner scan
a lot earlier but it skips right over my second scan.nextLine()
after scan.nextInt()
. I don't understand why it skips over it?
System.out.println("Something: ");
String name = scan.nextLine();
System.out.println("Something?: ");
int number = scan.nextInt();
System.out.println("Something?: ");
String insurer = scan.nextLine();
System.out.println("Something?: ");
String another = scan.nextLine();
推荐答案
因为当你输入一个数字
int number = scan.nextInt();
你输入一些数字并点击,它只接受数字并保持缓冲区中的新行字符
you enter some number and hit , it only accepts number and keeps new line character in buffer
所以 nextLine()
只会看到终结符字符,它会认为它是空字符串作为输入,修复它在处理 int
so nextLine()
will just see the terminator character and it will assume that it is blank String as input, to fix it add one scan.nextLine()
after you process int
例如:
System.out.println("Something?: ");
int number = scan.nextInt();
scan.nextLine(); // <--
这篇关于Java - Scanner - 跳过我上次的nextLine()请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!