scanner 调用完next 为何不能再调用nextline

编写如下测试代码:

import java.util.Scanner;

public class TestScanner {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//调用next
int n=scan.nextInt();
//调用nextLine
String m = scan.nextLine();
System.out.println(m);
}

}
运行结果:
没调用nextLine与调用nextLine的结果对比图:

从效果图上可以明显看出调用nextLine时输出了一个空行。

总结:
数据读取的过程图:

根据上图,可以知道在调用next时输入的是2加一个回车键,next是不会读取回车键\n的,但是这个回车键还在缓存区中, 因此再调动nextLine时,nextLine会读取这个回车键。所以才会出现 调用完next 不能再调用nextline的假象。

关键:next不会读取\n,nextLine会读取\n



猜你喜欢

转载自blog.csdn.net/weixin_42228338/article/details/80507287