- Reference/tutorial
- I would like to count the number of items in each different form (Froze, Fresh, ...).
- But unfortunately I do not know all of the classes.
- I could use
private static void CountTypes() {
if(fruitType.equals("Fresh")) {
freshCount ++;
}
if (fruitType.equals("Frozen")) {
frozenCount++;
}
}
- But unfortunately this does not identify missing classes.
- I can change it just a bit
if(fruitType.equals("Fresh")) {
freshCount ++;
} else if (fruitType.equals("Frozen")) {
frozenCount++;
} else if (fruitType.equals("Canned")) {
cannedCount++;
} else if (fruitType.equals("Dried")) {
driedCount++;
} else if (fruitType.equals("Juice")) {
juiceCount++;
} else {
System.out.printf("%s is unknown\n", fruitType);
}
- But that is really ugly.
- The Switch statement
switch (expression) {
case literal1:
statements;
break;
case literal2:
statements;
break;
...
default:
statements;
break;
}
- It is cleaner
- It will identify if you have duplicate cases.
private static void CountTypes() {
switch (fruitType) {
case "Fresh":
freshCount++;
break;
case "Frozen":
frozenCount++;
break;
case "Canned":
cannedCount++;
break;
case "Dried":
driedCount++;
break;
case "Juice":
juiceCount++;
break;
default:
System.out.printf("%s is an unknown type\n",fruitType);
break;
}
}