如果玩家掷硬币赢或输,java输出错误
如果玩家在我的掷硬币游戏中赢了或输了,我会尝试获得正确的输出。游戏将虚拟硬币翻转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();
}
}
}
# 1 楼答案
这条线似乎是你的问题。你在测试最后一次投币是赢还是输,而不是谁的总投币量更高
换成