JAVA 实现Readable接口的适配和Scanner的取用

 1 import java.io.IOException;
 2 import java.nio.CharBuffer;
 3 import java.util.Random;
 4 import java.util.Scanner;
 5 class RandomInt implements Readable
 6 {
 7     static int count=10;
 8     Random random=new Random(46);
 9     @Override
10     public int read(CharBuffer cb) throws IOException {
11         Integer i=random.nextInt(20);
12         cb.append(i.toString());    //向缓冲区中添加内容
13         cb.append(" ");
14         count--;
15         if(count==0) return -1; //-1表示中止
16         return i.toString().length()+" ".length(); //返回一次append的字符串长度
17     }
18 }
19 public class Main{
20     public static void main(String[]args)
21     {
22         Scanner s=new Scanner(new RandomInt());
23         while(s.hasNext())
24         {
25             System.out.println(s.next());
26         }
27     }
28 }

输出:

13
7
15
15
2
18
5
3
2
14

 

posted @ 2018-01-20 15:30  我也想学编程  阅读(192)  评论(0编辑  收藏  举报