I am very new to java. But i have been given a requirement to map student with their respective id, as key value pair.
When the user enters the required id, the system would print the student name associated with it. if no name is found associated with id(no value with key), it would print the student is not available.
****The program is not working when i am using sc.nextLine instead of sc.next in the same code to read the string line for student name input and an arrayoutofbound exception is generated. ****
Example of the flow:
Enter the number of student:
4(say)
Enter the id of the student:
11
12
13
14
Enter the number of the student name:
4(say)
Enter the name of the students:
Tom
Harry
Jim
Jerry
Enter a student id:
14(say)
The output would be:
the key is 11 and value is Tom
the key is 12 and value is Harry
the key is 13 and value is Jim
the key is 14 and value is Jerry
the value of the id 14 is jerry
.Can you please help me out in this?
Program:
public class HashMapDemo {
public static void main(String args[]){
// fill the code
int a,i=0,c,e;
Scanner sc = new Scanner(System.in);
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
System.out.println("Enter the number of student");
a = sc.nextInt();
System.out.println("Enter the student id");
int[] b = new int[a];
for (i=0;(i<b.length);){
b[i] = sc.nextInt();
i++;
}
System.out.println("Enter the number of student name available");
c = sc.nextInt();
System.out.println("Enter the student name");
String[] d = new String[c];
for (i=0;i<d.length;i++){
//if i am using sc.nextLine instead of sc.next araayoutofbound //exception is generated
d[i] = sc.next();
}
System.out.println("Enter the student id");
e = sc.nextInt();
for (i=0;i<c;i++)
{
hmap.put(b[i], d[i]);
}
System.out.println("The values are:"+hmap);
Set set = hmap.entrySet();
Iterator it = set.iterator();
while(it.hasNext()){
Map.Entry me = (Map.Entry)it.next();
System.out.println("key is:"+me.getKey()+" & value is: "+me.getValue());
}
String var = hmap.get(e);
System.out.println("The value of id is:"+var);
}
}