Enjoy that :oD
(You will have better to don't save grades as pure strings :) )
public enum Grades {
APLUS("A+"),A("A"),AMINUS("A-"),
BPLUS("B+"),B("B"),BMINUS("B-"),
CPLUS("C+"),C("C"),CMINUS("C-"),
DPLUS("D+"),D("D"),DMINUS("D-"),
EPLUS("E+"),E("E"),EMINUS("E-"),
FPLUS("F+"),F("F"),FMINUS("F-");
String stringVal;
private Grades(String stringVal) {
this.stringVal = stringVal;
}
@Override
public String toString() {
return this.stringVal;
}
}
public static void main(String[] args) {
HashMap<String,Grades> studentGrades= new HashMap<>();
studentGrades.put("Alvin", Grades.APLUS);
studentGrades.put("Alan", Grades.A);
studentGrades.put("Becca", Grades.AMINUS);
studentGrades.put("Sheila", Grades.BPLUS);
try {
//A+
System.out.println(getGradeByStudentName("Alvin", studentGrades));
} catch (Exception e) {
System.out.println("Student not found");
}
try {
//true
System.out.println(isStudentGrade("Becca", Grades.AMINUS,studentGrades));
} catch (Exception e) {
System.out.println("Student not found");
}
}
/**
* Obtain grade by the student name
* @param studentName name of the student
* @param source source data
* @return {@link Grades} value
* @throws Exception throws exception while student not found or data source is null
*/
public static Grades getGradeByStudentName(String studentName,HashMap<String, Grades> source) throws Exception{
if(source!=null && source.containsKey(studentName)){
return source.get(studentName);
}
throw new Exception("Student not found in database or null input data");
}
/**
* Get boolean value if given student in param has grade in param
* @param studentName name of the student
* @param expectedGrade expected grade
* @param source input source data
* @return true, if there is student with given name and has grade in parameter, false if there is a student but has another grade
* @throws Exception if data source is null or student with given name is not found
*/
public static boolean isStudentGrade(String studentName, Grades expectedGrade, HashMap<String, Grades> source) throws Exception{
Grades grade = getGradeByStudentName(studentName, source);
return grade.equals(expectedGrade);
}
FYI
For iterate over Keys and values in hashmap you can use following
HashMap<String, String> mapName = new HashMap<>();
for (String actualKey : mapName.keySet()) {
//eg. String value = mapName.get(actualKey);
}
for (String actualVal : mapName.values()) {
}
.get("")to get an entry from the map, and you can useequals()to compare objectsif ("A+".equals(studentGrades.get("Alvin"))) { ... }for (Map.Entry<String, String> entry: studentGrades.entrySet()) {, and then useentry.getKey()andentry.getValue()to get the key and value respectively.