关于Readable接口的read()方法
import java.util.*;
import java.nio.*;
public class RandomWords implements Readable{
private static Random rand = new Random(47);
private static final char[] capitals =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
private static final char[] lowers =
"abcdefghijklmnopqrstuvwxyz".toCharArray();
private static final char[] vowels =
"aeiou".toCharArray();
private int count;
public RandomWords(int count){this.count = count;}
public int read(CharBuffer cb){
if(count-- == 0)
return -1;
cb.append(capitals[rand.nextInt(capitals.length)]);
for(int i = 0; i < 4; i++){
cb.append(vowels[rand.nextInt(vowels.length)]);
cb.append(lowers[rand.nextInt(lowers.length)]);
}
cb.append(" ");
return 10;
}
public static void main(String[] args){
Scanner s = new Scanner(new RandomWords(10));
while(s.hasNext()){
System.out.println(s.next());
}
}
}
有这么一个程序,请各位耐心看一下,书上的一个例子。
我想问的是read()方法是什么时候被调用的(应该是自动调用的吧)
它是怎么调用的?(据我猜测应该是在read()方法得到-1的返回值之前会一直重复调用,并往scanner中加入数据)
请高手指导。
------解决方案--------------------hasNext()方法会调用read();
http://lihaozy.blog.51cto.com/1112871/285597