Why is my simple if statement not working?

I developed a simple card game in which two cards are displayed, and the user must bet on whether they will receive a card located between the two displayed cards. If the user does not want to bet, they simply decide again. The user starts at £ 100.
The game works great in most aspects, but has a huge flaw. The user can make bets more than in the balance. So, if a user has £ 100, they bet £ 105 and they win, they will have £ 205 in their balance. This is clearly bad ! And if they have 100 pounds, they bet 105 pounds and they lose, the balance remains unchanged. This is also very bad.
So I thought a simple if statement would sort this:

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; } 

Why is this not working? I'm pretty sure this is something very simple, but I'm pretty new to C #, so it's easy on me!

+6
c # if-statement
source share
4 answers

You should have else :

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

Your if statement is correct, however you do not complete it if it was called.

You can do this by adding "return;" after setting the label, or if you depend on the code under what you show us, you can include the switch statement in the "else" part of the if-statement ...

+3
source share

After the if statement, you move on to the case argument anyway, shouldn't you have else around the case / statement?

+2
source share

I do not understand for sure, but try

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

or

 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; } } 
+2
source share

All Articles