【发布时间】:2021-01-22 19:08:39
【问题描述】:
我制作了一个程序,让用户进行 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);
}
}
}
}
【问题讨论】:
-
这不是您的问题,但您需要在每次迭代后重置
isHeads和isTails,否则它们最终都会卡在true。为什么不只使用一个变量true表示正面,false表示反面,从而避免这种风险?编辑:实际上,这就是确切的问题。让我把这个写下来。 -
您好,您的问题得到解答了吗?如果是这样,您能否接受并投票赞成答案?如果不是,可以澄清什么?
标签: for-loop if-statement integer