You have a list of Student ID numbers followed by the course number (separated b
ID: 3589076 • Letter: Y
Question
You have a list of Student ID numbers followed by the course number (separated by a space) that each student is enrolled in. The listing is in no particular order. For instance, if student 1 is in CS100 and CS200 while student 2 is in CS105 and MATH210, then the list might look like this: 1 CS100 2 MATH210 2 CS105 1 CS200 Write a program that reads data in this format from the console. If the ID number is-1, then stop inputting data. Use the HashMap class to map from an Integer (the student ID number) to an ArrayList of type String that holds each course that the student has enrolled in. The declaration should look like the following: Map students = new HashMap0; After all the data is inputted, iterate through the map and output the student ID number and all courses stored in the vector for the student. The result should be a list of courses organized by the student ID number.Explanation / Answer
import java.util.*;
import java.io.*;
public class MyClass {
public static void main(String args[]) {
//Create HashMap to store data
Map<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();
//use BufferedReader to read data from console
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
//we need to catch IO exceptions as we are reading from console
try{
//input till you encounter -1
while(true){
//read each line
String name = input.readLine();
//split each line into key and value
String[] values = name.split(" ");
int key = Integer.parseInt(values[0]);
//input is -1 then stop reading
if(key==-1){
break;
}
String val = values[1];
//input key if not exists else add val
if (map.get(key) == null) {
map.put(key, new ArrayList<String>());
map.get(key).add(val);
}
else{
map.get(key).add(val);
}
}
}catch(IOException e){
System.out.println("IO Exception");
}
//Print all courses for each student
for (Map.Entry<Integer, ArrayList<String>> entry : map.entrySet()) {
System.out.print(entry.getKey()+" - ");
for(String course : entry.getValue()){
System.out.print(course+" ");
}
System.out.println();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.