Reputation: 3
I have a switch
statement which works fine, but I feel like it's poorly formatted and redundant(many of the cases do the same thing). How can I improve this?
switch (number) {
case 10: // do 1
break;
case 12: // do 2
break;
case 13: // do 1
break;
case 15: // do 3
break;
case 17: // do 2
break;
case 18: // do 2
break;
}
Upvotes: 0
Views: 136
Reputation: 1433
I guess you can group the cases with the same output together. It is one way to improve this.
switch (number) {
case 10:
case 13:
// do 1
break;
case 12:
case 17:
case 18:
// do 2
break;
case 15:
// do 3
break;
}
break;
is used to terminate a case in the switch statement. So, the cases will have same output when there is no break;
between them.
Upvotes: 3
Reputation: 2490
You can add default case. When provided cases are not equal to number default statement is executed. Code:
int number = 0;
switch (number) {
case 10: // do 1
break;
case 12: // do 2
break;
case 13: // do 1
break;
case 15: // do 3
break;
case 17: // do 2
break;
case 18: // do 2
break;
default:
System.out.println(number);
}
Upvotes: 1
Reputation: 792
You could improve it by removing a few break statement, like this
switch (number) {
case 10:
case 13: // do 1
break;
case 12:
case 17:
case 18: // do 2
break;
case 15: // do 3
break;
}
Upvotes: 3
Reputation: 8068
You may make it a bit more compact like this:
switch (number) {
case 10:
case 13:
System.out.println("do 1 + " + number);
break;
case 12:
case 17:
case 18:
System.out.println("do 2 + " + number);
break;
case 15:
System.out.println("do 3 + " + number);
break;
}
And the last break;
is not required in your case but good practice anyways for defensive programming.
Upvotes: 2