java - How do I add a value to a hash set? -
i'm working on practice problem requires me add value hashmap. can't figure out why keep getting error message on line coursename.add(student);
here code:
public class studentdatabase { // add instance variables private map<string, hashset<integer>> datacontent = new linkedhashmap<string, hashset<integer>>(); // prints report on standard output, listing courses , // students in each. if map empty (no courses), prints message // saying instead of printing nothing. public void report() { if (datacontent.isempty()) { system.out.println("student database empty."); } else { (string key : datacontent.keyset()) { system.out.println(key + ":" + "\n" + datacontent.get(key)); } } } // adds student course. if student in course, no change // if course doesn't exist, adds database. public void add(string coursename, integer student) { if (datacontent.containskey(coursename)) { coursename.add(student); } else { set<integer> ids = new hashset<integer>(); ids.add(student); datacontent.put(coursename, ids); } } }
ok, construct:
if (datacontent.containskey(coursename)) { coursename.add(student); }
is whacky. want is:
if (datacontent.containskey(coursename)){ set<integer> studentsincourse = datacontent.get(coursename); studentsincourse.add(student); }
should fix it.
Comments
Post a Comment