user3311613
user3311613

Reputation: 147

Trouble on getting my for loop to work

I am attempting to do a coin toss simulator but no matter what I do this for loop gets skipped and returns 0 heads and 0 tails. The randNumgenerator is defined before but I don't think it has anything to do with my issue.

Note: "not working" never shows up while I am running it, so I'm assuming it's a problem with the loop itself and not what's inside of the loop. I've also set the loop exit condition to 4 even though when this program is finished it will execute any amount of coin tosses the user wants.

here is my section of code. Can anyone tell me why I always get 0 heads and 0 tails?

final int sidesOfCoin = 2;
int flipsDone = 0;
int heads = 0;
int tails = 0;
int randomCoinValue;

for (heads = 0 ; flipsDone == 4; flipsDone++){
    randomCoinValue = randNumGenerator.nextInt(sidesOfCoin);
    if(randomCoinValue == 0){
        heads++;
    }
    else if(randomCoinValue == 1){
        tails++;
    }
    else{
        System.out.println("not working");
    }
}

System.out.println(heads + " heads and " + tails + " tails means " + (((double)heads * 100)/flipsDone) + "% tosses were heads");

Upvotes: 1

Views: 63

Answers (1)

Petar Minchev
Petar Minchev

Reputation: 47363

Shouldn't it be flipsDone <= 4? Otherwise you are exiting the loop immediately.

Upvotes: 6

Related Questions