Domanda

I'm trying to create a Java program that flips two coins to see who wins the coin flip. It prompts the user for a number of coin flips. If the first player has heads and the second player has tails, then it should output “Player 1 Wins!” and vice versa. If the two players have both heads or tails then it should output “Tie.”. Finally, it should keep track of the number of wins for each player and output the win rates after all coin flips have been made. It feels like the coin flipping part works, but when it displays the final scores for each player, the scores are never right. Can anyone find something wrong?

package coinflip;

import java.util.Scanner;

public class CoinFlip {

    public static void main(String[] args) {
        int flips;
        int flipscount=0;
        int p1score=1;
        int p2score=1;

        Scanner scan = new Scanner(System.in);
        System.out.println("How many flips: ");
        flips=scan.nextInt();

        CoinMethods Coins = new CoinMethods();

        while (flipscount!=flips)
        {
            flipscount++;

            Coins.flip();

            System.out.println(""+Coins.result()+"");

            if (Coins.p1isHeads()&&Coins.p2isTails())
            p1score++;

            if (Coins.p1isTails()&&Coins.p2isHeads())
            p2score++;
        }

        System.out.println("Player 1 won "+p1score+" times!");
        System.out.println("Player 2 won "+p2score+" times!");
    }
}

The CoinMethods class looks like:

package coinflip;

public class CoinMethods {

    private final int HEADS=0;
    private final int TAILS=1;
    private int p1face, p2face;

    public CoinMethods ()
    {
        flip();
    }

    public void flip()
    {
        p1face=(int) (Math.random()*2);
        p2face=(int) (Math.random()*2);
    }

    public boolean p1isHeads (){
        return p1face==HEADS;
    }

    public boolean p2isHeads (){
        return p2face==HEADS;
    }

    public boolean p1isTails (){
        return p1face==TAILS;
    }

    public boolean p2isTails (){
        return p2face==TAILS;
    }

    public String result()
    {
        String results;
        if (p1face==HEADS&&p2face==TAILS)
            {results="Player 1 wins!";
                }
        else
            if ((p1face==HEADS&&p2face==HEADS)||(p1face==TAILS&&p2face==TAILS))
            {results="Tie!";
               }
            else
            {results="Player 2 wins!";
                }

        return results;
    }
}
È stato utile?

Soluzione

It seems to me you need to initialize scores to zero instead of one:

int p1score=0;
int p2score=0;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top