9. Coin toss

Write a coin toss game

Your program should take a user's guess of whether the coin flip will be heads or tails, then randomly choose the results of a coin flip. If the user was right, it should print Victory! Otherwise, it should print Defeat..

When you've done that, change your program to print Victory! if the user gets two out of three guesses right.

Then, modify your program so that if the user gets the first two guesses right or wrong, the game automatically ends (since they've already won/lost at that point).

Coding tips

Code a few lines, then compile and run, then code a few more. Add lots of print statements as you go to make sure everything is working before you move on. Don't let errors sit - fix them before you keep going.

Some people write their entire programs and then run them for the first time when they're done. But if you do this and you get a bunch of errors, you won't have any idea where they are. If you instead run your program as you go and test thoroughly, if you get any errors, you'll know that they'll probably be in the most recent section you've written.

Coding this way will save you a huge amount of time and a lot of frustration.

Choosing a random move

One way to do this is to make your program randomly pick either 0 or 1, then have an if-statement that selects the coin flip result:

int random = ...; // some code to randomly pick 0 or 1
String result = "heads";
if (random == 1) {
    result = "tails";
}

Note that in the above snippet, we don't need to check if random is equal to 0 because we've already set the result variable to "heads".

Google around for how to generate random integers.

Solution

When you've coded up a full solution or you've gotten as far as you can, check out this page to see my solution. Don't click that link until you've given this problem a good try. Reading code is no substitute for coding. You can't learn to code if you don't code.