我有一個簡單的事實生成隨機事實的Java項目。 當點擊隨機按鈕時,我想顯示一個隨機事實,並找到該事實編號。生成隨機數組值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
也許'返回事實[I]'? –
你正在調用'Random.nextInt()'兩次。一次存儲我,並再次得到一個事實。你應該只能這樣調用一次。 –
與[從數組中獲取隨機值]完全相同(http://stackoverflow.com/questions/36825021/getting-a-random-value-from-an-array) –