Java – Scanner – 跳过我上次的nextLine()请求
所以我早先实例化了Scanner scan
但它在scan.nextLine()
之后跳过我的第二个scan.nextInt()
。 我不明白为什么它会跳过它?
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();
你输入一些数字并按Enter键 ,它只接受数字并在缓冲区中保留换行符号
所以nextLine()
只会看到终结符字符并且它会假设它是空白字符串作为输入,修复它在处理int
之后添加一个scan.nextLine()
例如:
System.out.println("Something?: "); int number = scan.nextInt(); scan.nextLine(); // <--
当你调用int number = scan.nextInt();
它不会消耗已被推送的回车符,所以这是在下一个scan.nextLine();
你想要你的代码
.... System.out.println("Something?: "); int number = scan.nextInt(); scan.nextLine(); // add this System.out.println("Something?: "); String insurer = scan.nextLine();
* nextInt()方法不会消耗新的行字符\ n。因此,在忽略nextInt()之前缓冲区中已存在的新行字符。
*接下来当你在nextInt之后调用nextLine()时,nextLine()将使用旧的新行
留下的角色,考虑结束,跳过其余的。
解
int number = scan.nextInt(); // Adding nextLine just to discard the old \n character scan.nextLine(); System.out.println("Something?: "); String insurer = scan.nextLine();
要么
//将字符串明确地解析为interger
String name = scan.nextLine(); System.out.println("Something?: "); String IntString = scanner.nextLine(); int number = Integer.valueOf(IntString); System.out.println("Something?: "); String insurer = scanner.nextLine();
之前给出的所有答案或多或少都是正确的。
这是一个紧凑版本:
你想做什么: 首先使用nextInt()
,然后使用nextLine()
发生了什么:当nextInt()
等待你的输入时,你输入整数后按ENTER
键。 问题是nextInt()
识别并只读取数字,因此ENTER
键的\n
在控制台上留下。 当nextLine()
再次出现时,你希望它等到它找到\n
。 但你没有看到的是,由于nextInt()
的不稳定行为, \n
已经在控制台上 [这个问题仍然作为jdk8u77的一部分存在]。
因此,nextLine读取空白输入并继续前进。
解决方案: 每次使用scannerObj.nextLine()
后,始终添加scannerObj.nextInt()