2016-04-25 98 views
-1

我有一個簡單的事實生成隨機事實的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

+0

也許'返回事實[I]'? –

+0

你正在調用'Random.nextInt()'兩次。一次存儲我,並再次得到一個事實。你應該只能這樣調用一次。 –

+6

與[從數組中獲取隨機值]完全相同(http://stackoverflow.com/questions/36825021/getting-a-random-value-from-an-array) –

回答

0

試試這個:

public String randomButton() { 
    Random random = new Random(); 
    i = random.nextInt(facts.length); 
    return facts[i]; 
} 
1

你產生兩個不同的號碼。只需使用i

i = random.nextInt(facts.length); 
return facts[i]; 
0

這會解決您的問題。每次你做一個random.next(facts.length)調用,它可以讓你兩個隨機數和他們是一樣的概率較小

public String randomButton() { 
    Random random = new Random(); 
    return facts[random.nextInt(facts.length)]; 
} 
0
// Remember, facts.length returns how many elements in the array 
// and new Random.nextInt() will generate a new result on every call 

// These are your facts: 

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.", 
}; 


// Here you get a random fact 
public String getRandomFactWithNumber() { 
    // Generate a random number between 0 and facts.length 
    int factNumber = new Random.nextInt(facts.length); 

    // Return the fact with its number 
    return "Fact " + factNumber + ": " + facts[factNumber]; 
} 

// And if you only want a fact, without the number 
public String getRandomFact() { 
    // Generate a random number between 0 and facts.length 
    int factNumber = new Random.nextInt(facts.length); 

    // Return the fact 
    return facts[factNumber]; 
}