0

I'm trying to make a simulator for statistics and, to begin with, I want to draw a number from 0 to 2 where each has the same odds of being drawn (i.e 0 = 33.33%, 1 = 33.33% and 2 = 33.33%) but when I run my code (for a million draws) I always get 0 is drawn 33% of the time, 1 is drawn 66% and c is drawn 1%.

For a million draws, I'd expect (with some variance) that each one of the number is drawn close to 33%.

this is what I got for the code:

    Random number = new Random();
    int sorteio;
    int a=0;
    int b=0;
    int c=0;
    int n;


    for (n=0;n<1000000;n++){
    sorteio = number.nextInt(3);

    switch (sorteio){
    case 0:
        a++;
    case 1:
        b++;
    case 2:
        c++;
    }

}
    System.out.println("a: " + a + " b: " + b + " c: " + c);

1 Answers1

1

Your switch statement needs break statements to prevent fall-through.

What is happening is that if 0 is generated, a is incremented and then because there is no break statement, execution "falls through" to the next case where b is incremented, and finally execution falls through again and c is incremented.

For the same reason, if 1 is generated, then b and c are both incremented. If 2 is generated, only c is incremented. For this reason, c will be incremented 100% of the time, 66% for b, and your desired 33% for c (because it is only intcremented when 1 is generated).

For more information on how switch statements work in Java, have a look at this tutorial.

Try this:

switch (sorteio) {
    case 0:
        a++;
        break;
    case 1:
        b++;
        break;
    case 2:
        c++;
        break;
}

If incrementing an int is all you intend to do in your switch, you might be better off to just use an array:

int[] count = new int[3];
for(int i=0; i<1000000; ++i) {
    count[number.nextInt(3)]++;
}

System.out.printf("a: %d, b: %d, c: %d%n", count[0], count[1], count[2]);
Zach Olivare
  • 3,805
  • 3
  • 32
  • 45