我有一个简单的事实Java项目,可以生成随机事实。 单击随机按钮时,我想显示一个随机事实,并找到该事实编号。
String factNumber[] = {
"Fact 1",
"Fact 2",
"Fact 3",
"Fact 4",
"Fact 5",
};
public String randomButtonNumber() {
return factNumber[i];
}
String facts[] = {"Elephants are the only mammals that can't jump.",
"Candles will burn longer and drip less if they are placed in the freezer a few hours before using.",
"Potatoes have more chromosomes than humans.",
"You burn more calories sleeping than you do watching television.",
"Animals that lay eggs don't have belly buttons.",
};
public String randomButton() {
Random random = new Random();
i = random.nextInt(facts.length);
return facts[random.nextInt(facts.length)];
}
现在,我的代码生成一个随机事实,但事实数字保持在1。
答案 0 :(得分:1)
您正在生成两个不同的数字。只需使用i
i = random.nextInt(facts.length);
return facts[i];
答案 1 :(得分:0)
试试这个:
public String randomButton() {
Random random = new Random();
i = random.nextInt(facts.length);
return facts[i];
}
答案 2 :(得分:0)
这可以解决您的问题。每次你进行random.next(facts.length)调用时,它会得到两个随机数,并且它们相同的概率较小
public String randomButton() {
Random random = new Random();
return facts[random.nextInt(facts.length)];
}
答案 3 :(得分:0)
buf = 'original'
def change_buf(new_val):
global buf
buf = new_val