zoukankan      html  css  js  c++  java
  • Scanner 与 Readable 的read()方法

          Readable接口中的read()方法实现了将字符串读入charBuffer中,但是只有在需要输出的时候才会调用。

          Scanner是文本扫描器类,利用Scanner扫描并输出charBuffer中的内容的顺序:以hasNext()方法为例:第一次调用 hasNext(),由于此时charBuffer并无内容,等待输入,hasNext()方法阻塞,调用并执行read()方法,执行完read()方 法,根据read方法的返回值来确定是否hasNext()的返回值是true或者false:若read()返回值不为-1,则认为hasNext() 为true,并且继续调用read()方法;若read()返回值为-1,则认为hasNext()为false,不再调用read()方法。

         另外,在输出时是根据下一个空格标记(cb.append(" "))为准,未读到空格标记之前,无论调用多少次read()方法,都不会输出,直到read()f方法返回-1或者读到空格标记,就会输出之前很多次通 过read()方法加到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;

    }

    }

  • 相关阅读:
    优化SQL查询:如何写出高性能SQL语句
    动态库与静态库
    多线程程序中fork导致的一些问题
    合理的使用size_t可以提高程序的可移植性和代码的可读性,让你的程序更高效。
    linux下C++ STL hash_map的使用以及使用char *型变量作为Key值的一大“坑”
    阅读腾讯编程规范的笔记
    2、vector的实现
    linux下C++对线程的封装
    1、空间配置器
    SQL Server三种表连接原理
  • 原文地址:https://www.cnblogs.com/wzyxidian/p/4383292.html
Copyright © 2011-2022 走看看