2016-04-25 18 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

のですか? –

+0

あなたは 'Random.nextInt()'を2回呼びます。一度私を保管し、もう一度事実を得るために。あなたはたぶんこれを一度だけ呼び出すべきです。 –

+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

次の2つの異なる番号を生成しています。ちょうど使用i

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

これはあなたの問題を解決するでしょう。 `;あなたはrandom.next(facts.length)呼び出しを行うたびに、それはあなたの2個の乱数を取得し、それらの確率が同じであることは、たぶん、` [i]は事実を返す

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]; 
} 
関連する問題