有的时候会发现 Scanner 的 next* 方法有 “bug”:还没等用户输入,系统就给了一个空白字符的默认值。
next* 指的是 next()、nextInt()、nextDouble() 这些。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("输入1:");
String next = input.next();
System.out.println("next():" + next);
System.out.print("输入2:");
String nextLine = input.nextLine();
System.out.println("nextLine():" + nextLine);
input.close();
}
例如上面的代码,会发现 nextLine 方法自动获取到了回车Enter
输入1:hello
next():hello
输入2:nextLine():
进程已结束,退出代码0
这是因为 nextLine() 方法和其他 next* 方法获取的内容不一样。
Scanner 阻塞程序的运行,等待并把用户的输入写入缓冲区,Scanner 从缓冲区读取内容,next* 方法会以空白字符作为结束标识,截取并返回结束标识前的内容,但会把结束标识留在缓冲区中。
空白字符有:空格、tab键、回车键等
nextLine() 方法顾名思义,用来获取一行内容,理所当然以 Enter 作为结束标识。跟其他 next* 方法不一样,它会把结束标识前的内容联通结束标识一同截取,但返回的时候不带结束标识,相当于丢弃了。
上面的例子就可以理解了:
- 输入字符串:hello,回车后 next() 方法以回车符作为结束标识,并把回车留在了缓冲区
- 第二次 nextLine() 方法来获取,发现缓冲区有 next() 方法 “残留” 的回车符,获取并丢弃回车符,第二次默认就是空了
这是个不小心会容易踩坑的点。
如何解决?
也容易。next* 方法读取后残留的空白符,它自己读取没有问题,因为空白符在开头会被忽略(所以 next* 不适合读取空字符串);nextLine() 这个老实人就惨了,它会把空白符老老实实读给自己。但我们又可以利用它读取空白符并丢弃的特点,额外使用一个 nextLine() 方法把空白符过滤掉。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("输入1:");
String next = input.next();
System.out.println("next():" + next);
input.nextLine(); // 额外代码用来过滤Enter
System.out.print("输入2:");
String nextLine = input.nextLine();
System.out.println("nextLine():" + nextLine);
input.close();
}
现在可以正常输入
输入1:hello
next():hello
输入2:world
nextLine():world
进程已结束,退出代码0
另外一个我个人认为容易歧义的点就是,next* 方法是获取结束标识前的内容,但并不是说结束标识后的内容就丢了。上面的例子就说明了这点,否则也不会出现第二次 “默认输入空白” 的情况。
遍历取所有值的 hasNext() 方法就更能说明问题:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("输入:");
String s1 = input.next();
System.out.println(s1);
System.out.println("==================");
while (!input.hasNext("#")) {
String s2 = input.next();
System.out.println(s2);
}
input.close();
}
输出结果:
输入:hello world good morning place holding
hello
==================
world
good
morning
place
holding
很明显的感觉到,第一次 next() 取走了 "hello",后面留在缓冲区,第二次 next() 读取就不需要用户的输入,而是把剩下的内容依次读取出来。