...

/

More Examples of the switch Statement

More Examples of the switch Statement

In this lesson, we will look at examples of the switch statement with a character or an enumerated data type.

Character values with a switch statement

The action of a switch statement can be based upon a character. For example, if the char variable grade contains a letter grade, the following switch statement assigns the correct number of quality points to the double variable qualityPoints:

Press + to interact
public class Example
{
public static void main(String args[])
{
double qualityPoints;
// Assume that the variable grade contains a character that ranges from 'A' to 'F'
char grade = 'D';
switch (grade)
{
case 'A':
qualityPoints = 4.0;
break;
case 'B':
qualityPoints = 3.0;
break;
case 'C':
qualityPoints = 2.0;
break;
case 'D':
qualityPoints = 1.0;
break;
case 'F':
qualityPoints = 0.0;
break;
default:
System.out.println("grade has an illegal value: " + grade);
qualityPoints = -9.0;
System.exit(0);
} // End switch
System.out.println("The grade " + grade + " represents " + qualityPoints + " quality points.");
} // End main
} // End Example

📝 Note: Why does the default case assign a value to qualityPoints ?

Without this assignment in the previous switch statement, or if we choose to omit the default case altogether, the compiler will think it possible for qualityPoints to remain uninitialized after the switch statement. We will get a syntax error. Another way to avoid the syntax error is to initialize qualityPoints to a value before the switch statement.

Checkpoint question

1.

The previous switch statement assumes that grade contains an uppercase letter ranging from A to Z. How can we accommodate letter grades given in either uppercase or lowercase without changing either switch (grade) or the value of grade?

Show Answer
Q1 / Q1
Did you find this helpful?

Checkpoint question

1.

In the previous switch statement, would it be reasonable to replace the statements in the default case with one assert statement? Explain.

Show Answer
Q1 / Q1
Did you find this helpful?

Checkpoint question

1.

If you could assume that grade’s value was only 'A', 'B', 'C', 'D', or 'F' prior to execution of the previous switch statement, would it be reasonable to replace the statements in the default case with the following assert statement? Explain.

assert false : "grade has an illegal value: " + grade;
Show Answer
Q1 / Q1
Did you find this helpful?

Omitting break in a switch

...