The relationship between Scanner and Readable's read() method

The relationship between Scanner and Readable's read() method

The read() method in the Readable interface implements reading the string into the charBuffer, but it is only called when it needs to be output.

Scanner is a text scanner class, using Scanner to scan and output the sequence of the content in the charBuffer: take the hasNext() method as an example: the hasNext() is called for the first time, because there is no content in the charBuffer at this time, waiting for input, the hasNext() method Block, call and execute the read() method. After executing the read() method, determine whether the return value of hasNext() is true or false according to the return value of the read method: if the return value of read() is not -1, it is considered hasNext() is true, and continue to call the read() method; if the return value of read() is -1, then 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 read, no matter how many times the read() method is called, it will not be output (the characters in the cache will always be Accumulation), until the read()f method returns -1 or a space mark is read, the string that was added to the charBuffer through the read() method many times before will be output.

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; // Indicates end of input
    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; // Number of characters appended
  }
  public static void main(String[] args) {
    Scanner s = new Scanner(new RandomWords(5));
    while(s.hasNext()) {
        System.out.println(s.next());
    }
  }
}

Guess you like

Origin blog.csdn.net/weixin_43743650/article/details/100539786