logo

Java Math.random() メソッド

java.lang.Math.random() 0.0 以上 1.0 未満の疑似乱数 double 型数値を返すために使用されます。デフォルトの乱数は常に 0 ~ 1 の間で生成されます。

値の範囲を指定したい場合は、返された値に範囲の大きさを乗算する必要があります。たとえば、0 ~ 20 の範囲の乱数を取得したい場合、望ましい結果を得るには、結果のアドレスを 20 倍する必要があります。

構文

 public static double random( ) 

戻る

 It returns a pseudorandom double value greater than or equal to 0.0 and less than 1.0. 

例1

 public class RandomExample1 { public static void main(String[] args) { // generate random number double a = Math.random(); double b = Math.random(); // Output is different every time this code is executed System.out.println(a); System.out.println(b); } } 
今すぐテストしてください

出力:

 0.2594036953954201 0.08875674000436018 

例 2

 public class RandomExample2 { public static void main(String[] args) { // Generate random number between 0 to 20 double a = Math.random() * 20; double b = Math.random() * 20; // Output is different every time this code is executed System.out.println(a); System.out.println(b); } } 
今すぐテストしてください

出力:

 19.09244621979338 14.762266967495655 

例 3

 public class RandomExample3 { public static void main(String[] args) { // Generate random number between 5 to 30 double a = 5 + (Math.random() * 30); double b = 5 + (Math.random() * 30); // Output is different every time this code is executed System.out.println(a); System.out.println(b); } } 
今すぐテストしてください

出力:

 21.30953881801222 29.762919341853877