mardi 29 octobre 2019

Coin flipping program incorrect result [duplicate]

This question already has an answer here:

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 "Correct" if the result is tails, and not whether or not the input matches the result. So my code seems to have a twist in there somewhere.

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

            if (guess == "heads") {
                headsOrTails = heads;
            }
            if (guess == "tails") {
                headsOrTails = tails;
            }

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

            if (heads == correct) {
                result = correct;
            }
            else {
                result = incorrect;
            }
            if (tails == correct) {
                result = correct;
            }
            else {
                result = incorrect;
            }
        return result+"you guessed "+guess+cointoss;
    }

Any help or pointers would be great. Thanks.

Aucun commentaire:

Enregistrer un commentaire