[問題] Thinking in Java 4th 的一個範例

看板java作者 (阿瑜)時間11年前 (2014/07/21 20:25), 編輯推噓0(002)
留言2則, 2人參與, 最新討論串1/1
完整程式碼如下: 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) { 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(10)); while(s.hasNext()) System.out.println(s.next()); } } 輸出: Yazeruyac Fowenucor Goeazimom Raeuuacio Nuoadesiw Hageaikux Ruqicibui Numasetih Kuuuuozog Waqizeyoy public int read(CharBuffer cb) 是implement Readable來的, RandomWords的constructor沒有呼叫它, 也沒有看到呼叫Readable的constructor 我的疑問是它在哪裡被呼叫的呢? 麻煩版上朋友的幫我解惑了,謝謝。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.133.120.146 ※ 文章網址: http://www.ptt.cc/bbs/java/M.1405945500.A.8A9.html

07/21 20:35, , 1F
s.next() -> n = source.read(buf); source就是RandomWord
07/21 20:35, 1F

07/22 00:46, , 2F
感謝,我去找code來看
07/22 00:46, 2F
文章代碼(AID): #1JpGQSYf (java)
文章代碼(AID): #1JpGQSYf (java)