问题描述
我制作了一个程序,在该程序中,用户有 10 轮机会,可以通过下注赚取尽可能多的钱。用户下注,然后选择正面或反面。循环有时会起作用,但有时它不会从总金额中增加或减少赌注。 for 循环是跟踪所有的输赢还是什么?
代码如下:
package wallonsproject;
import java.util.Scanner;
public class WallonProject {
public static void main(String[] args) {
// Todo Auto-generated method stub
Scanner userInput = new Scanner(system.in);
int totalMoney = 100000;
//Coin faces
boolean isHeads = false;
boolean isTails = false;
//CoinToss result
int coinTossResult;
//number of rounds
int numOfRounds = 10;
for(int i = 0; i < numOfRounds; i++)
{
//Betting and user Choice
System.out.println("How much would you like to bet?");
int userBet = userInput.nextInt();
//User bet must be less than the total money they have or else game exits
if(userBet > totalMoney)
{
System.exit(0);
}
System.out.println("Press 1 for heads,or 2 for tails");
int userChoice = userInput.nextInt();
System.out.println("Your starting money is " + totalMoney);
//coinToss
double coinToss = Math.random();
{
if(coinToss >= 0.5)
{
isHeads = true;
System.out.println("Toss is heads");
coinTossResult = 1;
System.out.println("The toss is " + coinTossResult);
}
if(coinToss < 0.5)
{
isTails = true;
System.out.println("Toss is tails");
coinTossResult = 2;
System.out.println("The toss is " + coinTossResult);
}
System.out.println("You chose " + userChoice);
//All different outcomes of WINNING results
if(isHeads == true && userChoice == 1)//if your choice is heads and cointossresult is heads
{
System.out.println("You win");
totalMoney = totalMoney + userBet;
}
if(isTails == true && userChoice == 2)//if your choice is tails and cointossresult is tails
{
System.out.println("You win");
totalMoney = totalMoney + userBet;
}
//All different outcomes of LOSING results
if(isHeads == true && userChoice == 2)
{
System.out.println("You lose");
totalMoney = totalMoney + userBet;
}
if(isTails == true && userChoice == 1)
{
System.out.println("You lose");
totalMoney = totalMoney - userBet;
}
System.out.println("You bet " + userBet);
System.out.println("Your total money is " + totalMoney);
}
}
}
}
解决方法
在 for 循环之外,定义两个变量:
boolean isHeads = false;
boolean isTails = false;
在循环内部,如果你翻转了正面,你就使 isHeads
为真,如果你翻转了尾部,你就使 isTails
为真。不幸的是,您永远不会重置这些,因此它们会“卡住”在 true
位置。
因为它们被卡住了,所以您后来遇到了条件列表中的两个条件,而不仅仅是一个。您先加后减赌注,所以总分不会改变。
还有一件小事:
if(isHeads == true && userChoice == 2)
{
System.out.println("You lose");
totalMoney = totalMoney + userBet;
}
就在那里,您可能想减去赌注,就像您进一步做的那样。
这不是修复代码的最干净的方法,但它是最少的输入:作为循环中的最后一条指令,您应该将 isHeads
和 isTails
都设置为 {{1 }}。更简洁的方法需要进行一些重构:只需使用一个对正面为真,对反面为假的变量,这样就可以避免这种风险。然后每次你翻转时,你都会重置它。