Card 02/ 09
All 9 cards
ExampleDifficulty: Beginner1 min
A Grade From a Score, With if and else if
A score out of a hundred becomes a letter. The boundaries overlap on purpose, and the ladder is what stops that mattering.
int score = 74;
String grade;
if (score >= 90) {
grade = "A";
} else if (score >= 70) {
grade = "B";
} else if (score >= 50) {
grade = "C";
} else {
grade = "fail";
}
System.out.println(grade);BSeventy-four satisfies two of those conditions — it is at least seventy and at least fifty. Only one branch runs, because else if means "and none of the ones above matched". Rungs are tried top to bottom and the first true one wins.
The thing being tested is a range, not an exact value, and a range is what an if ladder exists for.