Scanner的本质是依赖于正则表达式的,他会将扫描的数据放在缓冲区中,根据空格符进行匹配区分。
1)next() 会自动过滤空格、tab、enter等结束符,直至遇到有效字符之后,空格、tab、enter等会视为结束符
2)nextLine() 读取到回车才结束
3)nextInt() 只读取数值,回车会被存在缓冲区中
Scanner sc = new Scanner(System.in);
//==========================================
System.out.println("输入:nextInt");
int arr = sc.nextInt();
//===================================
System.out.println("输入:next");
String str = sc.next();
//===================================
System.out.println("输入:nextLine");
String str1 = sc.nextLine();
输出结果:
输入:nextInt
111
输入:next
tfgyhjuk
输入:nextLine
next()和nextInt()的结束符都会存再缓存中,当我们在他们后面使用nextLine()时,nextLine()会自动读取缓存中的回车符,然后结束读取任务,所以nextLine()并不是没有执行。
为了避免这种事情,我们可以这样使用下面这种情况。
System.out.println("输入:nextInt");
int arr = sc.nextInt();
sc.nextLine(); //读取上个nextInt留下的回车符