我正在尝试创建一个翻转两个硬币的Java程序,以查看谁赢得了硬币翻转。它会提示用户进行多次硬币翻转。如果第一个玩家有头并且第二个玩家有尾巴,那么它应该输出“玩家1胜利!”,反之亦然。如果两个玩家都有头或尾,那么它应该输出“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;
}
}
答案 0 :(得分:1)
在我看来,您需要将分数初始化为零而不是一分:
int p1score=0;
int p2score=0;