LoginSignup
1
0

More than 3 years have passed since last update.

【Java】ランダムメソッド

Posted at

Javaに初めから用意されているクラス、java.util.Random java.lang.Math
この2つがあります。

今回はMathクラス(java.lang.Math)のランダムメソッドについて簡単な説明をします。
Math.random()
ポイント
・戻り値の型は double
・0.0 ~ 1.0未満 の範囲で乱数を取得します


①double rand = Math.random();
②double rand = Math.random() * 10;
③int rand = (int)(Math.random() * 10);

①戻り値の型がdoubleなので変数の型は基本doubleでないとコンパイルエラーとなります。
②0.0から10.0未満の範囲で乱数を取得する場合、ランダムメソッドの後に * 10 をつけます。
③整数での乱数を取得する場合、②をint型にキャストする必要があります。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0