Results 1 to 3 of 3
Like Tree1Likes
  • 1 Post By Norm

Thread: How to simplify these switch statement?

  1. #1
    dojob is offline Member
    Join Date
    Jul 2013
    Posts
    52
    Rep Power
    0

    Default 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[0]++; break;
                    case 3: sum[1]++; break;
                    case 4: sum[2]++; break;
                    case 5: sum[3]++; break;
                    case 6: sum[4]++; break;
                    case 7: sum[5]++; break;
                    case 8: sum[6]++; break;
                    case 9: sum[7]++; break;
                    case 10: sum[8]++; break;
                    case 11: sum[9]++; break;
                    case 12: sum[10]++; break;
                }
            }

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,435
    Rep Power
    25

    Default 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
    dojob likes this.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    dojob is offline Member
    Join Date
    Jul 2013
    Posts
    52
    Rep Power
    0

    Default Re: How to simplify these switch statement?

    Thanks I have found the way to do it

Similar Threads

  1. Replies: 3
    Last Post: 11-19-2012, 08:12 PM
  2. The Switch Statement
    By Everyman in forum New To Java
    Replies: 11
    Last Post: 04-20-2012, 03:29 PM
  3. Replies: 2
    Last Post: 03-26-2012, 04:27 PM
  4. switch statement
    By droidus in forum New To Java
    Replies: 2
    Last Post: 09-21-2011, 09:54 AM
  5. Switch Statement Help
    By bluegreen7hi in forum New To Java
    Replies: 6
    Last Post: 02-06-2008, 05:16 AM

Posting Permissions

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