Switch Statements

An alternative to nesting conditionals is a structure called a switch statement. A switch statement takes an integer or character variable and allows for different cases, or options, for the value of the variable. There is also a default case that "catches" any values not specified in a case. The general form of a switch is:
switch(variable) { case ___: <code for case>; //__is replaced by an int or 'char' value case ___: <code for case>; case ___: <code for case>; default: <code for default>; }
Switch statements also utilize the keyword break to keep the flow from "falling" into the other cases. So, unless the programmer desires code from other cases to execute, use the break at the end of each case. Here is an example that assigns a letter grade based on a score out of 10: switch(score) { case 10: case 9: letterGrade='A'; //score of 10 will 'fall' into case 9 break; case 8: letterGrade='B'; break; case 7: letterGrade='C'; break; case 6: letterGrade='D'; break; case 5: case 4: case 3: case 2: case 1: case 0: letterGrade='F'; //scores of 1-5 will 'fall' into case 0 break; default: System.out.println("Not a valid score"); }