Switch uses a jump-table internally, that is why case statements can only test for exact and final values. You can imagine this like this:
result = jumpTable[key]; // switch pseudo-code
This is not what you'll find in the compiled code, but it is the same idea in general, so I use it to answer your question.
Any index that is not in this array cannot be accessed, so if you have an array of length 5 you cannot do something like:
result = jumpTable[2.3]; // impossible in Java
because this is just not defined and Java cannot magically figure out that you actually wanted to round down to 2. To archive that you need to write a function that can understand and convert intermediate values, for example a simple floor function
result = jumpTable[floor_int(2.3)]; // a solution for a specific case
would do the trick for some cases. It is obvious that the function used needs to actually fit your problem, so if 2.3 should point to index 1, you obviously need to use a different math behind the scene.
As assylias wrote, the method floorEntry
of a TreeMap is a generalized version of what I wrote above and can be used to solve your problem.
The alternative is a standard if-else chain like this:
String getTestResult(final double avg) {
if (avg >= 3.5) {
return "A Pass";
} else if (avg >= 3.0) {
return "B Pass";
} else if (avg >= 2.5) {
return "C Pass";
} else if (avg >= 2.0) {
return "D Pass";
} else {
return "Fail";
}
}
This uses the natural ordering of numbers, which states that (obviously) avg
cannot be >= 3.5 and <= 3.5 at the same time.
For your case you should probably just write a function gradeToIndex
, then use that in place of the floor_int
function as in my example above, something like
index = (int) Math.round((avg - 2.0) * 2.0);