# Thread: How to simplify these switch statement?

1. Member Join Date
Jul 2013
Posts
52
Rep Power
0

## How to simplify these switch statement?

From the following code, we can see the pattern case(i+2): sum[i]++;
My question is how to simplify it to above statement? assuming that there are 10000 case, it would not be a good idea to type case 2 ..... case 10000;

Java Code:
```        for (int i = 0; i < rolls; i++){
switch(rollDice(n)){
case 2: sum++; break;
case 3: sum++; break;
case 4: sum++; break;
case 5: sum++; break;
case 6: sum++; break;
case 7: sum++; break;
case 8: sum++; break;
case 9: sum++; break;
case 10: sum++; break;
case 11: sum++; break;
case 12: sum++; break;
}
}```  Reply With Quote

2. ## Re: How to simplify these switch statement?

Why use a switch statement if the relationship between the case value and the index is a constant?
index = caseValue - 2;
Use an if to detect the case 0 and 1 values  Reply With Quote

3. Member Join Date
Jul 2013
Posts
52
Rep Power
0

## Re: How to simplify these switch statement?

Thanks I have found the way to do it  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•