I have a HashMap called examList
which stored exam grades of each course a student took. The key of this hashmap is courseID
, and the value is an array list gradeList
which contains all grades a student got in a course. The problem is as follows:
// Add a new course exam listing
// where each course exam can be done a max 5 times
protected void addExam(String courseID, int grade) {
ArrayList<Integer> gradeList;
// First check if course is in the list, if not add it
if ( !examList.containsKey(courseID) ) {
gradeList = new ArrayList<Integer>();
examList.put(courseID, gradeList);
examList.get(gradeList.add(grade));
// If course is already on the list, check if max number of attempts has been reached, if not add new grade
} else if ( examList.containsKey(courseID)) {
if ( gradeList.size() <= 5 ) // THIS IS WHERE ERROR OCCURES
examList.get(gradeList.add(grade)); // HERE ALSO
else
System.out.println("Maxim number of attempts has been reached.");
}
}
As you can see I first define gradeList, but I do not yet initialize it. Under IF I check if student has already done this exam before. If he hasn't then new entry is created for hashmap, and gradeList is finally initialized. Under ELSE (where, it is considered that there is an element with gradeList already initialized) I just add new grade. However, that seems to be the problem. I can't compile it because program presumes that gradeList is not yet initialized here. So, how can I fix this? Or can I avoid it (since logically, gradeList will always be initialized under ELSE) through error handling, of which I know little about?
ArrayList<Integer> gradeList = null;
In your case, it's better to do something as follows:
List<Integer> gradeList = examList.get(courseID);
if(gradeList == null) {
gradeList = new ArrayList<Integer>();
//... do something
} else {
//... do something else
}
just initialize gradeList when you create the variable.
ArrayList<Integer> gradeList = new ArrayList<Integer>();
or set it to null
ArrayList<Integer> gradeList = null;
Assign null
in its declaration:
ArrayList<Integer> gradeList = null;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With