-2

I need to write a program that simulates 1000 coin tosses, then prints the resulting number of heads and tails. My main problem is with the "for" loop. This is what I have so far:

public static void main(String[] args) {
    int tosses;
    int headsTails = 0;
    int tails = 0;
    int heads = 0;

    for (tosses = 0; tosses < 1000; tosses ++, headsTails = (int) (Math.random() * 2) + 1);
    {
        if (headsTails == 1) {
            heads ++;
        } else {
            tails ++;
        }
    }

    System.out.println("You flip a coin 1000 times.\nNumber of heads:" + heads + "\nNumber of tails:" + tails);

}

When I run this, I get either:

You flip a coin 1000 times.
Number of heads:0
Number of tails:1

or:

You flip a coin 1000 times.
Number of heads:1
Number of tails:0

So the program is only "tossing the coin" once. How would I go about making this program work as intended?

2
  • 2
    Your statements are not inside the for loop. Remove the ; at the end of for declaration.
    – Codebender
    Aug 2, 2015 at 4:26
  • A hint: debugging would've shown the issue immediately Aug 2, 2015 at 4:34

1 Answer 1

2

You have a semicolon after the for. This makes the statements inside your {} not be a part of the loop. Generally speaking, even though the syntax is correct, your code will be less confusing if you only have the loop increment inside the last block of the for loop.

With both of these changes:

for (tosses = 0; tosses < 1000; tosses ++)
{
    headsTails = (int) (Math.random() * 2) + 1;
    if (headsTails == 1) {
        heads ++;
    } else {
        tails ++;
    }
}
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.