日期:2014-05-20  浏览次数:20759 次

java中的scanner中的一道题
大家请看下面一段java代码:
public static void main(String[] args){
Scanner s=new Scanner(System.in);
  int x=0;
while(x<4){
String str=s.next();
System.out.println(str);
x++;
}
我只知道Scanner对象的.next方法是用来读取string的,按照我的理解,他和Scanner对象的nextLine方法的最大差别我觉得就是next每次读取一个String对象,而nextLine则每次读取一行。这样的话我认为程序应该这样跑:
假使我先输入abc,然后我再输入空格,
这个时候便会println这个abc,
然后接着输入,比如输入“def”,
这个时候便会println这个def
.....
直到输入四次满为止
但是事实却不是这样
事实却是这样的:
输入"abc def ghi jkl"
打印出来的便是
abc
def
ghi
jkl
但是程序是顺序执行的,这种情况是为什么呢?难道它读取的字符串先存储在某个缓冲区?希望对Scanner有研究的大师帮助下我这个菜鸟,谢谢!

------解决方案--------------------
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
也许是这个
------解决方案--------------------
查看api吧
------解决方案--------------------
他默认的吧 空格当确定输入完毕使用了估计是
------解决方案--------------------
在没按enter前,方法一直阻塞,而不是按空格就触发执行
------解决方案--------------------
next和nextLine的区别是
nextLine是读入一行,也就是遇到\n或者\r\n字符为止
next是读与一个字符串,缺省遇到\\s空白字符[ \t\n\x0B\f\r] 为止,也就是空格符或者\t,\n等等
所以输入
"abc def ghi jkl"
每next一次就会按空格符来依次取进一个字符串,因为循环4次,所以就刚好依次取了4个字符串,否则如果输入数据不够,还会继续等待用户输入