the Read () method in the readable interface implements the reading of the string into the Charbuffer, but it is only called when output is required.
Scanner is a text scanner class that uses scanner to scan and output the order of content in Charbuffer: Take the Hasnext () method as an example: the first call to Hasnext (), because at this time Charbuffer has no content, wait for input, Hasnext () Method blocks, invokes and executes the read () method, executes the read () method, and determines whether the return value of Hasnext () is true or false, based on the return value of the Read method: If the read () return value is not 1, then Hasnext () is considered true, and continues to call the Read () method; if the read () return value is-1, hasnext () is considered false, and the read () method is no longer called.
In addition, the output is based on the next space mark (Cb.append ("")), before the space mark is not read, no matter how many times the Read () method is called, it will not be output until the read () F method returns 1 or a space mark, it will be output many times through read () The string that the method adds to Charbuffer.
public class Randomwords implements readable{
public 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 static void Main (string[] args) {
Scanner s = new Scanner (new Randomwords (10));
while (S.hasnext ()) {
System.out.println (S.next ());
}
}
@Override
public int read (Charbuffer cb) throws IOException {
TODO auto-generated Method Stub
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;
}
}
Scanner and Readable's read () method