1. 程式人生 > >JAVA Random 隨機類

JAVA Random 隨機類

nextInt 方法 得到一個隨機整數, 可以指定範圍

package object;
import static net.util.Print.*;
import java.util.Random;

public class Test{
    public static void main(String[] args){
        Random rand = new Random();
        for(int i=0;i<100;i++){
        int j = rand.nextInt(100)+1;//呼叫Rand 方法 
        printnb(j+"\t");
        }
        
    }

}
/*******************here is Rand nextInt display **************************

public int nextInt(int bound) {
if (bound <= 0)
throw new IllegalArgumentException(BadBound);

 
 

int r = next(31);
int m = bound - 1;
if ((bound & m) == 0) // i.e., bound is a power of 2
r = (int)((bound * (long)r) >> 31);
else {
for (int u = r;
u - (r = u % bound) + m < 0;
u = next(31))
;
}
return r;
}*///~

 

nextFloat 方法 得到一個隨機浮點數,不能指定範圍

package object;
import static net.util.Print.*;
import java.util.Random;

public class Test{
    public static void main(String[] args){
        Random rand = new Random();
        for(int i=0;i<100;i++){
        float j = rand.nextFloat();
        printnb(j
+"\t"); } } } /*****************this is nextFloat show*********************** * public float nextFloat() { * return next(24) / ((float)(1 << 24)); * } *///~