Card 03/ 09
All 9 cards
ExampleDifficulty: Beginner1 min
A Shipping Rate From a Country Code, With switch
A two-letter code becomes a rate. There are no ranges here — a code either is "DE" or is not.
String country = "DE";
double rate = switch (country) {
case "UK" -> 2.99;
case "IE", "FR", "DE" -> 6.49;
default -> 14.99;
};
System.out.println(rate);6.49Three codes share one rate on line 5, written once. default catches everything that matched nothing, and in this arrow form the whole switch produces a value that is assigned straight into rate.
Put this beside the grade ladder and the shared part comes out: one thing was tested, the branches were mutually exclusive, and exactly one of them ran. What differs is only the question — a range in one, an exact match in the other — and that is what should decide which shape you write.