标签:ack har 字符 return 实现 pac new turn ret
通过implements(实现)Readbale interface(接口)的 read() method(方法) 实现自己添加字符到buffer里,然后读取
package object; //: interfaces/RandomWords.java // Implementing an interface to conform to a method. import java.nio.*; import java.util.*; 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) { //read()方法来自Readable接口,Sanner()里也有用到 if(count-- == 0) return -1; // Indicates end of input cb.append(capitals[rand.nextInt(capitals.length)]); //从cpitals里面每次读出一个字符并添加到buffer里面 for(int i = 0; i < 4; i++) { cb.append(vowels[rand.nextInt(vowels.length)]);//从vowels里面每次读出four char 字符并添加到buffer里面 cb.append(lowers[rand.nextInt(lowers.length)]);//append()方法:添加字符到buffer里面 } cb.append(" "); //空格和‘\n‘功能一样 return 10; // Number of characters appended } public static void main(String[] args) { Scanner s = new Scanner(new RandomWords(10));
// new RandomWords(10)可以换做任意实现了Readable接口的类所生成的对象 while(s.hasNext()) //hasNext()通过调用readInput()方法调用read()方法知道read()返回-1结束 System.out.println(s.next()); } } /* Output: Yazeruyac Fowenucor Goeazimom Raeuuacio Nuoadesiw Hageaikux Ruqicibui Numasetih Kuuuuozog Waqizeyoy *///:~
标签:ack har 字符 return 实现 pac new turn ret
原文地址:https://www.cnblogs.com/jiangfeilong/p/10213593.html