simple Java switch case

a simple problem that I encountered in Yahoo! Answers:

I want to go through the colors in my given Color [] colors; then once it goes through all 5 colors in the array, to start all over

Best solution I can think of is using a switch case:


//define Color[] colors = {color1, color2, color3, color4, color5};
int i=0;
while(true)
{
switch (i)
{
case 1: object.setColor(color1);
break;
case 2: object.setColor(color2);
break;
case 3: object.setColor(color3);
break;
case 4: object.setColor(color4);
break;
case 5: object.setColor(color5);
break;
default: object.setColor(color1); //when all else goes wrong
break;
}

if( i == 5 )
i = 1;
else
i++;
}

4 comments:

Loki said...
This comment has been removed by the author.
Loki said...

I think you can do away with the switch block and use the array.

    object.setColor(colors[i]);Final code would look like this:

    //define Color[] colors = {color1, color2, color3, color4, color5};
    int i = 0;
    while(true) {
        object.setColor(colors[i]);
        i = (i + 1) % 5;
    }

Loki said...

sorry for spamming, but let me tell you it's not easy writing code in comments. anyway, this is easier to read:

http://tinyurl.com/nbfvt7

Anonymous said...

that's even better haha I just didn't want to explain that kind of solution!

and about writing codes on comments or on blog posts, I'm still looking for a better way. I hate it when my indentations are messed up.