nextXXX()
在读取到有效字符前的空白格,它都不会读取的,直接跳过。
在读到有效字符后,遇到空格键、Tab键或Enter键等结束符,它就会结束读取。
读取内容是有效字符。将最后敲下的空白格永远地留在那里。
int s1=scan.nextInt();
System.out.print("是"+s1);
可以很清楚的看到,2前面的空白都没有读取。3也没有被读取,因为next的结束就是个空格键、Tab键或Enter键等结束符
nextLine()
能读取到空白格。 而且nextLine()方法的结束符只是Enter键,即nextLine()方法返回的是Enter键之前的所有字符,它是可以得到带空格的字符串的。
因此
int s1=scan.nextInt();
String s=scan.nextLine();
System.out.print("是"+s1+s);
输出结果是
nextLine()自动读取了被next()去掉的Enter作为他的结束符,所以没办法给s2从键盘输入值。经过验证,我发现其他的next的方法,如double nextDouble() , float nextFloat() , int nextInt() 等与nextLine()连用时都存在这个问题,解决的办法是:在每一个 next()、nextDouble()
、 nextFloat()、nextInt() 等语句之后加一个nextLine()语句,将被next()去掉的Enter结束符过滤掉。