如果玩家在我的抛硬币游戏中赢了或输了,我试图得到正确的输出。游戏将一枚虚拟硬币抛100次,如果玩家选择的硬币被抛次数最多的那枚获胜,如果次数较少,那么他们选择的硬币将会失败。但是输出总是出错。
public class Strategy extends Object {
/**
*
* Encoding for a strategy.
*/
int opponentLastMove = 1;
int myLastMove = 1;
String name;
// 0 = defect, 1 = cooperate
public Strategy()
{
} /* Strategy */
public int nextMove()
{
return 0;
} /* nextMove */
public void saveOpponentMove(int move) {
opponentLastMove = move;
}
public int getOpponentLastMove() {
return opponentLastMove;
}
public void saveMyMove(int move) {
myLastMove = move;
}
public int getMyLastMove() {
return myLastMove;
}
public String getName() {
return name;
}
}
public class StrategyRandom extends Strategy
{
/**
*
* Encoding for a strategy.
*/
// 0 = defect, 1 = cooperate
public StrategyRandom()
{
name = "Random";
} /* StrategyRandom */
public int nextMove()
{
if (Math.random() < 0.5)
return 1;
return 0;
} /* nextMove */
}
import java.util.Scanner;
public class GameDriver {
public static void main(String[] args) {
try {
StrategyRandom stratRandom = new StrategyRandom();
Scanner scanner = new Scanner(System.in);
int choice = 1;
int heads;
int tails;
int coinFlip = 0;
System.out.print("Enter your name: ");
stratRandom.name = scanner.nextLine();
System.out.println("Press 1 for Heads" + "nPress 2 for Tails"
+ "nPress 0 to Exit");
choice = Integer.parseInt(scanner.nextLine());
while (choice != 0) {
heads = 0;
tails = 0;
for (int i = 0; i < 100; i++) {
coinFlip = stratRandom.nextMove();
if (coinFlip == 0) {
heads++;
System.out.print("H,");
} else {
tails++;
System.out.print("T,");
}
}
if (coinFlip == 1) {
System.out.println("nYou Won");
} else {
System.out.print("nYou Lost");
}
System.out.println("nTimes head was flipped: " + heads);
System.out.println("Times tails was flipped: " + tails);
System.out.print("nHello " + stratRandom.getName()
+ ", Enter a number or 0 to exit: ");
choice = Integer.parseInt(scanner.nextLine());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
这一行似乎是您的问题。你是在测试最后一次抛硬币是赢还是输,而不是测试谁的总金额更高。
if (coinFlip == 1) {
System.out.println("nYou Won");
} else {
System.out.print("nYou Lost");
}
改为
if( choice == 1 ){
if (heads > tails)
System.out.println("nYou Won");
else if(tails > heads )
System.out.print("nYou Lost");
}else{
if ( heads < tails )
System.out.println("nYou Won");
else if( tails < heads )
System.out.print("nYou Lost");
}
if( heads == tails )
System.out.println(n"It is a tie!");