论坛首页 入门技术论坛

readable接口

浏览 1197 次
锁定老帖子 主题:readable接口
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-05-21  

Readable接口就是为了Scanner类专门创建的一个接口,使得Scanner的入口参数不必限于某个类。实现Readable接口要只需是实现public int read(CharBuffer cb)方法。当方法返回-1时候Scanner类停止读取。package com.liuc.test.think.chapter9;

import java.io.IOException;
import java.nio.CharBuffer;
import java.util.Random;
import java.util.Scanner;

public class RandomWords implements Readable{
	private Random rand=new Random(47);
	private static final char[] capitals="ABCDEFGHIJKLMOPQRSTUVWXYZ".toCharArray();
	private static final char[] lowers="ABCDEFGHIJKLMOPQRSTUVWXYZ".toLowerCase().toCharArray();
	private static final char[] vowels="aeiou".toCharArray();
	private int count;
	
	public RandomWords(int count) {
		this.count=count;
	}
	


	@Override
	public int read(CharBuffer cb) throws IOException {
		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 scanner=new Scanner(new RandomWords(10));
		while (scanner.hasNext()) {
			System.out.println(scanner.next());
			
		}
	}

}
 
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics