关于next(),nextLine()的区别:
next()从遇到第一个有效字符(非空格、换行符)开始扫描,遇到第一个分隔符或结束符(空格’ ‘或者换行符 ‘\n’)时结束。
举个例子:
Scanner sc = new Scanner(System.in);
//从键盘中输入的是hello world!
String str_1 = sc.next();
String str_2 = sc.nextLine();
System.out.println(str_1);
System.out.println(str_2);
运行上述代码,控制台操作如下:
我们发现next()方法,遇到空格符停止读取,因此留下空格加world!字符串,即" world!"
而nextLine()方法从空格开始读取,遇到换行符结束。所以保存在str_2里的是" world!"(world前有一个空格别忽略)。
下面来说说如何混合使用nextInt(),nextDouble(),nextLine()方法
直接上代码:
Scanner sc = new Scanner(System.in);
/*从键盘中输入的是:
* 12
* 0.96
* helloworld*/
int a=sc.nextInt();
double b=sc.nextDouble();
sc.nextLine();//为了清除掉0.96后面的换行符
String s= sc.nextLine();
System.out.println("Int:"+a);
System.out.println("Double:"+b);
System.out.println("String:"+s);
输出为:
12
0.96
helloworld
Int: 12
Double: 0.96
String: helloworld
此时输入电脑缓存中的数据格式为:
“ 12\n0.96\nhelloworld\n”
nextInt()方法,读取了整型数据12,还剩下"\n0.96\nhelloworld\n"
nextDouble()方法,读取了双浮点型数据0.96,还剩下"\nhelloworld\n"
如果此时直接用nextLine()读取,该函数遇到换行符\n就结束,即后面的"helloworld\n"将不会被读取。
所以需要在这之前输入nextLine(),去掉缓冲区的\n,然后再读取
因为nextLine()会读取\n之前的所有内容,并去除\n,而nextDouble()等不会去除它后面的\n