dimanche 22 janvier 2017

Generating random integer using nextBoolean in Java

I am trying to generate random integer between 1 to 512 using random bits from nextBoolean() in Java. But I am not able to generate random numbers greater than 64 with my code.

public static void main(String[] args) {
    int n=9, randInteger = 0, myInteger;
    Random rand = new Random();
    while(true){
        for(int i = 0; i <= n; i++){

            myInteger = (rand.nextBoolean()) ? 1 : 0;
            //Using base 2 for giving weights to bits and converting 
            //them to integer
            randInteger = randInteger+(2^n)*(myInteger);
            }
        if(randInteger <= 512 && randInteger > 0){
            break;              
            }
        }
    System.out.println("Random Integer "+randInteger);      

}




Aucun commentaire:

Enregistrer un commentaire