特定の範囲内でランダムな int
値を生成するにはどうすればよいですか?
以下のものを試してみましたが,うまくいきませんでした。
試み1:。
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
**2.2.2.2
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
Java 1.7以降**では、標準的には以下のような方法で行うことができます。
import java.util.concurrent.ThreadLocalRandom;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
関連するJavaDoc]4を参照してください。 この方法では,不適切な使い方をすると混乱やエラーの原因となるjava.util.Randomインスタンスを明示的に初期化する必要がないという利点があります。
しかし、逆に、シードを明示的に設定する方法がないため、テストやゲームの状態を保存する場合など、結果を再現することが難しい場合があります。 そのような場合には、Java 1.7以前の手法である以下の方法があります。
**Java 1.7以前の標準的な方法は、以下の通りです。
import java.util.Random;
/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* @param min Minimum value
* @param max Maximum value. Must be greater than min.
* @return Integer between min and max, inclusive.
* @see java.util.Random#nextInt(int)
*/
public static int randInt(int min, int max) {
// NOTE: This will (intentionally) not run as written so that folks
// copy-pasting have to think about how to initialize their
// Random instance. Initialization of the Random instance is outside
// the main scope of the question, but some decent options are to have
// a field that is initialized once and then re-used as needed or to
// use ThreadLocalRandom (if using at least Java 1.7).
//
// In particular, do NOT do 'Random rand = new Random()' here or you
// will get not very good / not very random results.
Random rand;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
関連するJavaDoc]1を参照してください。 実際には、java.util.Randomクラスの方がjava.lang.Math.random()よりも望ましい場合が多いです。
特に、標準ライブラリの中に乱数生成のためのわかりやすいAPIがある場合には、乱数生成のために車輪を再発明する必要はありません。
使う。
minimum + rn.nextInt(maxValue - minvalue + 1)
rand.nextInt((max+1) - min) + min;