如果玩家在我的硬币投掷游戏中赢了或输了,我试图获得正确的输出。游戏翻转一个虚拟硬币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();
}
}
}
答案 0 :(得分:0)
这条线似乎是你的问题。您正在测试最后一次硬币翻转是赢还是输,而不是谁的总金额更高。
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!");