# Can I use one switch for multiple expressions?

Printable View

• 11-30-2011, 05:08 PM
karibo
Can I use one switch for multiple expressions?
The tittle says it all!

At the moment I am working on a (noob) project to make a pokerdice game. I've made 5 objects (dices).
I need them now to run one by one in a switch check to make random numbers from 1-6 into king, dame, ace, etc...

My code in where the problem occurs.
Code:

```public void roll() {         Random rand = new Random();         dobbel1 = rand.nextInt(6) + 1;         dobbel2 = rand.nextInt(6) + 1;         dobbel3 = rand.nextInt(6) + 1;         dobbel4 = rand.nextInt(6) + 1;         dobbel5 = rand.nextInt(6) + 1;     }     public String toString(){         String resultaat;         switch (dobbel1){             case 1:                 resultaat = "aas";                 break;             case 10:                 resultaat = "Boer";                 break;             case 11:                 resultaat ="Dame";                 break;             case 12:                 resultaat ="Koning";                 break;             default:                 resultaat = "" + waarde ;         }         resultaat += " " + kleur;         return resultaat;     }```
So by switch (dobbel1) I would like to run all dobbel true it.
Maybe with a for lus?

How can I make this work? And I think 5 switches isn't the right answer ;)

I hope you understand me in this crappy english.

Thanks in advance
Karibo
• 11-30-2011, 05:10 PM
Fubarable
Re: Can I use one switch for multiple expressions?
Rather than dobbel1, dobbel2, ... why not an array: int[] dobbels = new int[5], then use a for loop to do the code above for each dobbel in the array.
• 11-30-2011, 05:17 PM
karibo
Re: Can I use one switch for multiple expressions?
Wow thanks for fast response! :)

Yes i'm going to try this never seen arrays but it seems logic.

Thanks alot :)!