mercredi 30 octobre 2019

Coin flipping program only saying incorrect

I'm still new to Java, so apologies for the mess.

So a user would put in "heads" or "tails" into here:

System.out.println(labExample.headsOrTails("heads"));

And the program should randomly generate a heads or tails and also say whether or not your guess is correct. e.g. "Incorrect: you guessed heads and I flipped tails."

What I've made so far seems to only say that the guess is incorrect. Even when the guess matches. So I've definitely gone wrong somewhere, most likely the last few if/else statements.

public String headsOrTails(String guess) {
        String cointoss; //input and result
        String guessHeads = "heads"; //if guess == "heads"
        String guessTails = "tails"; //if guess == "tails"
        String coinHeads;
        String coinTails;
        String correct = "Correct: "; //if guess matches
        String incorrect = "Incorrect: "; //if guess doesn't match
        String result = ""; //end print of the result

            if (guess.equals("heads")) {
                guess = guessHeads;
            }
            if (guess.equals("tails")) {
                guess = guessTails;
            }

            if (Math.random() >= 0.5) {
                cointoss = " and I flipped heads";
                coinHeads = correct;
                coinTails = incorrect;
            }
            else {
                cointoss = " and I flipped tails";
                coinHeads = incorrect;
                coinTails = correct;
            }

            if ((coinHeads.equals(correct) && (guess.equals(guessHeads)))) {
                result = correct;
            }
            if ((coinTails.equals(correct) && (guess.equals(guessTails)))) {
                result = correct;
            }
            else result = incorrect; {

            }

        return result+"you guessed "+guess+cointoss;
    }

Any help or pointers would be amazing. Thanks.

Aucun commentaire:

Enregistrer un commentaire