|
同学们大家好,我们上课。这节课依然是数据结构的实验课。 - /**
- * HashMap例子
- * by Daniel Shiffman.
- *
- * 这个例子说明了并示范了如何使用 HashMap 去存储
- * 一个对象的集合,并用一个键值去检索. 这看起来非常像数组,
- * 只有代替访问元素的数字索引, 我们用一个字符串
- * 如果熟悉其他语言中的关联数组,
- * 这是同样的概念。
- *
- * 这个例子使用哈希映射了一个简单的集合
- * [url]http://en.wikipedia.org/wiki/Concordance_[/url](publishing)
- */
- // The next line is needed if running in JavaScript Mode with Processing.js
- /* @pjs font="Georgia.ttf"; */
- HashMap<String, Word> words; // HashMap 对象
- String[] tokens; // 从输入文件的所有单词的数组
- int counter;//计数器
- void setup() {
- size(640, 360);//设置窗口大小
-
- words = new HashMap<String,Word>();//对HashMap对象进行初始化操作
- // 读取文件并分割
- String[] lines = loadStrings("dracula.txt");
- String allText = join(lines, " ");//这句话的意思相当于allText=allText+lines+" ";
- tokens = splitTokens(allText, " ,.?!:;[]-");//去掉alltext中的,.?!:;[]-符号并把新的字符串返回给tokens
-
- // 创建字体
- textFont(createFont("Georgia", 24));
- }
- void draw() {
- background(51);
- fill(255);
-
- // 一次传送一个词
- String s = tokens[counter];
- counter = (counter + 1) % tokens.length;
- // 这个词是否在HashMap中
- if (words.containsKey(s)) {
- // 得到这个词的对象并增加计数器
- // 我们通过键值访问HashMap中的对象, String
- Word w = words.get(s);
- w.count();
- } else {
- // 否则做一个新的词在HashMap中
- Word w = new Word(s);
- // 添加元素到HashMap 用put()函数 有两个 两个参数, "key" and "value"
- // 这个key对于我们来说就是String, the value 就是 Word 对象
- words.put(s, w);
- }
- // x and y 将被用找出每一个单词
- float x = 0;
- float y = height-10;
- // 查看每一个单词
- for (Word w : words.values()) {
-
- // 每个单词只显示3次
- if (w.count > 3) {
- // 这个size就是count
- int fsize = constrain(w.count, 0, 100);
- textSize(fsize);
- text(w.word, x, y);
- // 在X轴上移动
- x += textWidth(w.word + " ");
- }
-
- //如果X上移动到边缘了,就移动Y轴
- if (x > width) {
- x = 0;
- y -= 100;
- // 如果y轴也移动满了我们就停止移动
- if (y < 0) {
- break;
- }
- }
- }
- }
- class Word {
-
- int count;
- String word;
-
- Word(String s) {
- word = s;
- count = 1;
- }
-
- void count() {
- count++;
- }
- }//
复制代码
效果如图,非常明显,就是单词出现的次数越多就变得越大。
好了,同学们下课。
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?注册
x
|