2

我正在尝试创建一个 Java 程序来翻转两个硬币,看看谁赢得了硬币翻转。它提示用户进行多次硬币翻转。如果第一个玩家有正面,第二个玩家有反面,那么它应该输出“Player 1 Wins!” 反之亦然。如果两个玩家都有正面或反面,那么它应该输出“Tie.”。最后,它应该跟踪每个玩家的获胜次数,并在所有掷硬币后输出获胜率。感觉就像掷硬币的部分一样有效,但是当它显示每个玩家的最终分数时,分数永远不会正确。任何人都可以发现问题吗?

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!");
    }
}

该类CoinMethods看起来像:

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;
    }
}
4

1 回答 1

1

在我看来,您需要将分数初始化为零而不是一:

int p1score=0;
int p2score=0;
于 2012-10-21T01:09:35.200 回答