【发布时间】:2017-07-19 01:37:46
【问题描述】:
我有这个程序,我需要来自外部文件的 50 个随机单词出现,每个单词随机移动到随机位置...我已经能够让每个单词彼此分开移动到随机位置,但是问题是只有外部文件中的第一个单词出现了 50 次,这是唯一出现的单词……而不是 50 个随机单词!只有 50 个相同的词...所以我尝试将 int index = int(random(allWords.length)); 放在 draw 下和 for 内,但这可能会导致它每秒发生 50 次、60 次,这不是我想要的发生...有人建议相反,我可能只想在 setup() 函数中生成一次随机词,我可以通过创建我创建的 class 的实例并将它们存储在数组或 ArrayList 中来做到这一点.问题是我仍然不太熟悉,所以有人有关于我如何做到这一点的提示,或者可能有一个链接,我可以在其中获得有关如何做到这一点的指南?
如果有人想看看我的问题是什么,这是我的代码...
String [] allWords;
int x = 120;
int y = 130;
int index = 0 ;
word [] words;
void setup () {
size (500, 500);
background (255); //background : white
String [] lines = loadStrings ("alice_just_text.txt");
String text = join(lines, " "); //make into one long string
allWords = splitTokens (text, ",.?!:-;:()03 "); //splits it by word
words = new word [allWords.length];
for (int i = 0; i < 50; i++) {
words[i] = new word (x, y);
}
}
void draw() {
background (255);
for (int i = 0; i < 50; i++) { //produces 50 words
words[i].display();
words[i].move();
words[i].avgOverlap();
}
}
class word {
float x;
float y;
word(float x, float y) {
this.x = x;
this.y = y;
}
void move() {
x = x + random(-3, 3); //variables sets random positions
y = y + random(-3, 3); //variables sets random positions
}
void display() {
fill (0); //font color: black
textAlign (CENTER, CENTER);
text (allWords[index], x, y, width/2, height/2 );
}
void ran () {
textSize (random(10, 80)); //random font size
}
}
【问题讨论】:
-
在 word.display() 的
text (allWords[index], x, y, width/2, height/2 );行中,index始终为 0(因为它在此程序中永远不会改变)。您应该将index或字符串本身传递给word()构造函数,以便每个实例都知道自己的。 -
@marekful 谢谢!
标签: arrays arraylist random processing text-size