【问题标题】:Why won't my simple if statement work?为什么我的简单 if 语句不起作用?
【发布时间】:2010-09-16 08:34:19
【问题描述】:

我设计了一个简单的纸牌游戏,其中显示了两张牌,用户必须下注他们是否会得到一张介于显示的两张牌之间的牌。如果用户不想下注,他们只需再次发牌。用户以 100 英镑开始。

该游戏在大多数方面运行良好,但有一个巨大的缺陷。用户可以下注超过他们的余额。因此,如果用户有 100 英镑,他们下注 105 英镑,他们赢了,他们的余额将有 205 英镑。这显然是糟糕!如果他们有 100 英镑,他们下注 105 英镑并且他们输了,他们的余额保持不变。这也很糟糕。
所以我认为一个简单的 if 语句可以解决这个问题:

if (wager > balance)
{
    winLoseLabel.Text = "You can't bet more than you have!";
}  
switch (betResult)
{
    case TIE:
        winloseLabel.Text = "Tie. You still lose. HA!";
        myRules.Balance -= wager;
        break;

    case PLAYERWINS:    
        winloseLabel.Text = "You win. Woop-de-do..";
        myRules.Balance += wager;
        break;

    case DEALERWINS:
        winloseLabel.Text = "You lose. Get over it.";
        myRules.Balance -= wager;
        break;
}

为什么这不起作用?我很确定这很简单,但我对 C# 还是很陌生,所以放轻松!

【问题讨论】:

    标签: c# if-statement


    【解决方案1】:

    你应该有一个else

    if (wager > balance)
    {
        winLoseLabel.Text = "You can't bet more than you have!";
    }
    else
    {  
        switch (betResult)
        {
            //...
        }
    }
    

    【讨论】:

    • @Dan Dumitru:哇,我显然一直盯着屏幕看很久,以至于我的大脑已经炸了。对不起我的愚蠢!谢谢!
    • @Christain W:我知道。您必须等待一段时间才能完成。
    • 是的,15 分钟。感谢大家的支持,但我认为现在没关系,我不应该再因为这个简单的答案而得到他们......
    • 不过还是帮了我!哦,我昨天发布了一个问题,它已经解决了一半,我已经编辑了它。如果人们能看一看,我将非常感激,这比我的纸牌游戏重要得多!
    • 抱歉,不知道时间限制。 :)
    【解决方案2】:

    您的 if 语句是正确的,但是,如果例程被触发,您不会结束它。

    您可以通过添加“return;”来做到这一点设置标签后的语句,或者,如果您依赖于向我们展示的代码,您可以在 if 语句的“else”部分中包含 switch 语句...

    【讨论】:

      【解决方案3】:

      在你的 if 语句之后你还是进入了 case 语句,你不应该在 case 语句/周围有一个 else 吗?

      【讨论】:

        【解决方案4】:

        我不是很明白,但是试试

        if (wager > balance)
        {
            winLoseLabel.Text = "You can't bet more than you have!";
            return;
        }  
        

        if (wager <= balance)
        {
            switch (betResult)
            {
                case TIE:
                    winloseLabel.Text = "Tie. You still lose. HA!";
                    myRules.Balance -= wager;
                    break;
        
                case PLAYERWINS:    
                    winloseLabel.Text = "You win. Woop-de-do..";
                    myRules.Balance += wager;
                    break;
        
                case DEALERWINS:
                    winloseLabel.Text = "You lose. Get over it.";
                    myRules.Balance -= wager;
                    break;
            }
        }  
        

        【讨论】:

          猜你喜欢
          • 2012-07-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-17
          • 1970-01-01
          • 2016-07-05
          相关资源
          最近更新 更多