More Examples of Multiway if Statements
Explore multiple solutions for multiway if statements in Java through an example that assigns letter grades based on numerical exam scores. Understand how different structures affect clarity, logic, and program robustness to improve your decision-making code.
We'll cover the following...
Example
Let’s consider part of a program that assigns a letter grade—A through F—to an integer exam score ranging from 0 to 100. Grades are assigned as follows:
- A 90 to 100
- B 80 to 89
- C 70 to 79
- D 60 to 69
- F Below 60
We offer five different solutions to this problem. Each one uses the variables
int score;
char grade;
and assumes that score contains an integer ranging from 0 to 100.
All solutions are correct, but not all are good, as we will see.
Solution 1
The first solution clearly indicates the range of scores for each letter grade. Run the program with various values of the score.
Solution 2
The second solution is similar to ...