I\'m learning Java through a series of explanations and exercises, and one of them was to create a program that would display a number grade (0-5) in accordance to a number
You can use a NavigableMap
, most commonly a TreeMap
. The method used below is floorEntry
. Quoting Javadoc:
Returns a key-value mapping associated with the greatest key less than or equal to the given key, or
null
if there is no such key.
Note: Your code was missing an =
sign on the 29 boundary, and the points
value should be an integer.
Changed to use a grade (0-5), instead of the string used in question.
// Grade boundary is lower-inclusive (grade is 0-60)
TreeMap gradeMap = new TreeMap<>();
gradeMap.put( 0, 0); // 0–29
gradeMap.put(30, 1); // 30–34
gradeMap.put(35, 2); // 35–39
gradeMap.put(40, 3); // 40–44
gradeMap.put(45, 4); // 45–49
gradeMap.put(50, 5); // 50+
System.out.println("Type the points [0-60]: ");
int points = reader.nextInt();
reader.nextLine();
int grade = gradeMap.floorEntry(points).getValue();
System.out.println("Grade: " + grade);