在下面的代码中,我尝试添加或减去用户投注(例如10美元)并更新余额。最初,余额将从100美元开始,当用户继续下注时,余额将更新,直到余额达到$ 0或用户决定退出。
以下代码在第一次下注时正常工作,但余额在第二次下注期间不会更新。任何帮助将不胜感激!
int balance = 100;
protected int PlayerBalance()
{
int totalBalance = 0;
if (CalculateWinAmount() > 0) //CalculateWinAmount() method returns the win amount. If no wins, the method return 0
{
totalBalance += CalculateWinAmount();
}
else
{
totalBalance -= BetAmount(); //BetAmount() method returns the amount the user has bet (e.g. $5, $10..)
}
return totalBalance += balance;
}
protected void DisplayPlayerBalance()
{
playerTotalAmountLabel.Text = PlayerBalance().ToString();
}
答案 0 :(得分:1)
您没有正确设置余额,因为@Mattew已在答案中指定。
作为重构的一部分,您不需要本地变量totalBalance
,因为您可以直接在balance
上操作。出于性能原因,你不应该两次致电CalculateWinAmount
。
重构代码:
static int balance = 100;
protected int PlayerBalance()
{
int winAmount = CalculateWinAmount();//CalculateWinAmount() method returns the win amount. If no wins, the method return 0
if (winAmount > 0)
{
balance += winAmount;
}
else
{
int betAmount = BetAmount();
balance -= betAmount; //BetAmount() method returns the amount the user has bet (e.g. $5, $10..)
}
return balance;
}
protected void DisplayPlayerBalance()
{
playerTotalAmountLabel.Text = PlayerBalance().ToString();
}
答案 1 :(得分:0)
您似乎没有设置余额:请尝试以下
int balance = 100;
protected int PlayerBalance()
{
int totalBalance = 0;
if (CalculateWinAmount() > 0) //CalculateWinAmount() method returns the win amount. If no wins, the method return 0
{
totalBalance += CalculateWinAmount();
}
else
{
totalBalance -= BetAmount(); //BetAmount() method returns the amount the user has bet (e.g. $5, $10..)
}
// Set the balance to the current balance + the new totalbalance
balance += totalBalance;
// return the balance figure
return balance;
}
protected void DisplayPlayerBalance()
{
playerTotalAmountLabel.Text = PlayerBalance().ToString();
}
答案 2 :(得分:0)
您从未更新 PlayerBalance 方法中的余额字段。
我建议只更新余额,而不是使用本地变量 totalBalance ,而不是如下:
protected int PlayerBalance()
{
if (CalculateWinAmount() > 0) //CalculateWinAmount() method returns the win amount. If no wins, the method return 0
{
balance += CalculateWinAmount();
}
else
{
balance -= BetAmount(); //BetAmount() method returns the amount the user has bet (e.g. $5, $10..)
}
return balance;
}