Alternative use of the switch function

I am writing a program to simulate a blackjack game, and I use the switch to go through the menu. It works well, but I am wondering if you can expand the switch to cover a few cases. For example, for each player there are many results. For example, blackjack, blackjack and blackjack, the bust player and the dealer do not break, dealer busts, but the player does not break, both with the player’s budget and the dealer, with a double recession and busts, etc. Is there a way to use the switch here when comparing multiple variables or do I need to add if / else-if with multiple conditions?

+4
source share
3 answers

By canceling your comment on @LeoCorrea, your conditions appear to be logical.

Maybe try something like:

final int PLAYER_BUST = 1 << 0; final int DEALER_BUST = 1 << 1; // ... int total = 0; total |= player.bust ? PLAYER_BUST : 0; total |= dealer.bust ? DEALER_BUST : 0; switch(total) { case 0: // neither player nor dealer has bust break; case PLAYER_BUST: // just player bust, so dealer wins break; case DEALER_BUST: // just dealer bust, so player wins break; case PLAYER_BUST | DEALER_BUST: // both have bust break; } 

1 << x is equal to 2 ^ x, and | - bitwise OR. My example is for n = 2, but n can be any reasonable number.

This is something like PHP encodes its error levels . Notice how most levels are represented in degrees 2 (with only one digit “1” in binary format).

We use | at these levels to get the combined result of n Booleans. Each bit in int total represents one of the conditions.

Since there are 2 ^ n possible combined outcomes of n Boolean ones, we can match each result with an integer of n bits. We cannot include n logical elements, but, fortunately, we can use switch for this integer total , which represents n Boolean elements.

+3
source

Unfortunately, switch for multiple variables is not possible in Java. Besides the suggested @irrelephant bit masks, you can try to rethink your assessment:

I am not completely familiar with Blackjack, but I think that instead of setting player.busted and similar fields, you can simply set the player’s score to -1 (or, if you get a rating of 30 worse than a rating of 25, you can set it to -score ), and then just compare the scores.


PS Instead

 if (player.bust == false && dealer.bust == true) 

you can just enter

 if (!player.bust && dealer.bust) 

This greatly saves writing and is much readable.

+1
source

I'm not sure what language you speak, because you did not specify it, but in Ruby, the case statement (works like a switch statement)

You can do something like

 case [A, B] when [true, true] then ... when [false, true] then ... 

You can also have several conditions for outputting the same output.

 case condition when ("a" and "b") # do something when "c" # do something end 

You are a very vague question, and I think you should consider making it more specific to the language you use.

0
source

All Articles