简体   繁体   中英

how to stop a message box from displaying if it goes over a certain number in c# visual studio?

i am doing a blackjack game for a college assignment. I'm still quite new to c#. i have two labels one for the dealers score and another for the players. I have the two values in the labels compare. when the dealer score is higher than players it displays a message saying the dealer wins. my problem is if the dealer goes over 21 the dealer still wins but it also displays the dealer bust message. How do i stop the message box from displaying after 21.

code:

private void BtnHold_Click(object sender, EventArgs e)
    {
        // declarations
        int DealerScore;


        Random randomizer = new Random();


        // get random
        DealerScore = randomizer.Next(17, 25);


        // dealer scores blackjack
        if (DealerScore == 21)
        {
            MessageBox.Show("Dealer Scored blackjack");
        }

        // dealer loses
        if (DealerScore > 21)
        {
            MessageBox.Show("Dealer bust. Player wins");

        }

        if (DealerScore > total)
        {

            MessageBox.Show("dealer wins");
        }


        if (total > DealerScore)
        {

            MessageBox.Show("Player wins");
        }



        // display in label
        LblDealerScore.Text = DealerScore.ToString();

Change the conditional statement to if else ladder. That should fix the problem.

Eg:

if (DealerScore == 21)
    {
        MessageBox.Show("Dealer Scored blackjack");
    }

    // dealer loses
    else if (DealerScore > 21)
    {
        MessageBox.Show("Dealer bust. Player wins");

    }

You need simple IF/ELSE

    if (DealerScore == 21)
    {
        MessageBox.Show("Dealer Scored blackjack");
    }

    // dealer loses
    else if (DealerScore > 21)
    {
        MessageBox.Show("Dealer bust. Player wins");

    }

The simplest solution would be adding an else if statement. For more information on some examples on how if/else statements work, please see below:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/if-else

// dealer scores blackjack
if(DealerScore == 21)
{
    MessageBox.Show("Dealer scored blackjack");
}
// dealer loses
else if(DealerScore > 21)
{
    MessageBox.Show("Dealer bust. Player wins");
}

Happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM