RandomlyKnighted RandomlyKnighted -4 years ago 122
Java Question

math.Random isn't working right

I'm trying to simulate a coin flip using the code below.

public class Coin
{
public static double result;
int[] count = new count[2];

public static void flip()
{
result = Math.random();
}

public static boolean isHeads()
{
if (result == 0.0)
{
count[0]++;
return false;
}

else
{
count[1]++;
return true;
}
}

public static void main(String[] args)
{
flip();
isHeads();
System.out.println(count[0]);
System.out.println(count[1]);
}
}


For some reason Eclipse says that the

import java.util.Random;

is never used even though I'm clearly using it. I didn't put my for loop into the code above but it loops n number of times and then outputs the result. No matter how many times it loops it always returns that the result is greater than 0.0 which can't be right. Am I calling Math.random incorrectly?

Answer Source

I'll recomend using

java.util.Random

public static void main(String[] args) throws Exception {
    Random rand = new Random();

    int headCount = 0;
    int tailCount = 0;

    for (int i = 0; i < 10; i++) {
        int value = rand.nextInt(2);

        if (value == 0) {
            System.out.println("Heads");
            headCount++;
        } else {
            System.out.println("Tails");
            tailCount++;
        }
    }

    System.out.println("Head Count: " + headCount);
    System.out.println("Tail Count: " + tailCount);

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download